In this article, we are going to learn how to consume the ASP.NET Core WEB API GET by Id Method in simple steps.

In previous article Consuming ASP.NET Core API GET Method in .Net Core Console Application we have see that GET Method API returns collection of data.

In GET by Id Method of WEB API normal is a method to which we are going to pass Id in URI and according to Id which we have passed it is going to return single result in response.

We already have a GET by Id API which is developed in ASP.Net Core we are going to consume this API in the .Net Core Console Application.

API which we are going to call

Let first call GET by Id API using Postman

URI: – https://localhost:44373/api/Music/1

If you see about URI, we have passed Id of Song which will return single song as show in response.

Creating Console Application

For Consuming APIs, we have created a .Net Core Application which Target Framework .Net 6.0 with name Console consumer

Steps to consume WEB API GET by Id we need.

  1. HttpClient class instance for sending HTTP Requests.
  2. Setting Base Address “https://localhost:44373
  3. Setting Accept Header “application/json”
  4. Adding a class with the name SongModel which has properties and fields of response json.
  5. Next, we are calling GetAsync Method and Passing Request Uri (“/api/Music/1”) to it which will send a GET request to the specified Uri in an asynchronous way.
  6. Added Newtonsoft.Json Nuget package
  7. DeserializeObject (response we are going to receive will be Json format which we need to map to .Net Type)

Method for Consuming API

In this method, we are going to set BaseAddress https://localhost:44373 along with Accept Headers as application/json and call GetAsync (“GET Method”) to the GetAsync() method we are going to pass the request, Uri “/api/Music/{songid}”.

As this method GetAsync() will get called we are going to receive a response and in this response, the first thing we are going to do is check the Status of it if it is a success then we are going to read the response and then Deserialize it.

As in GET method we use to get collection of data in response here in Get by Id Method we are going to get only Single object in response.

Code Snippet

 static async Task GetByIdData()
        {
            using var client = new HttpClient();
            client.BaseAddress = new Uri("https://localhost:44373");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            int songid = 1;
            HttpResponseMessage response = await client.GetAsync($"/api/Music/{songid}");
            if (response.IsSuccessStatusCode)
            {
                var responseBody = await response.Content.ReadAsStringAsync();
                try
                {
                    var song = JsonConvert.DeserializeObject<SongsModel>(responseBody);
                    if (song != null)
                    {
                        Console.WriteLine($"Name: {song.Name},Year: {song.Yearreleased}");
                    }

                    Console.ReadLine();
                }
                catch (JsonReaderException)
                {
                    Console.WriteLine("Invalid JSON.");
                }

            }
        }

Calling GetByIdData Method in Main() Method

 static void Main(string[] args)
 {
     GetByIdData().Wait();
 }

View of runtime receiving a response

Json object which we have received in response

Below snapshot after the deserializing Json object

In this article, we have learned how to consume the GET Method with a parameter named id in the .Net Core Console Application in simple steps with sample code.

Welcome my New Dotnet Shorts #DOTNETSHORTS Series Hope you like it small and simple and focused.

By Saineshwar

Microsoft MVP for Developer Technologies | C# Corner MVP | Code project MVP | Senior Technical Lead | Author | Speaker | Love .Net | Full Stack developer | Open source contributor.