Consuming RestAPI from .Net Console Applications

This is very common requirement in industry when we need to consume api from console application.

Let's create very basic Rest API using .net core.

I have used default template for creating .net core web api and we have weather forecast controller by default.

By Default, it has Get method as mentioned in screen below and i am not going in too much details

Running this application


Let's execute and below is output.


Consume from Console Applicaiton 

Creating Console Application


I have added Console application in same solution.


Here to consume Rest API we need to call Httpclient


var apiUrl = "https://localhost:44316/WeatherForecast"; // Example API endpoint using var client = new HttpClient(); try { // Making the GET request var response = await client.GetAsync(apiUrl); // Ensure the request was successful response.EnsureSuccessStatusCode(); // Read the response content as a string var content = await response.Content.ReadAsStringAsync(); Console.WriteLine(content); Console.ReadKey(); } catch (HttpRequestException e) { Console.WriteLine($"Request error: {e.Message}"); }

Explanation

HttpClient: An instance of HttpClient is created to make HTTP requests. It's important to reuse HttpClient instances when possible, as they are expensive to create and can lead to socket exhaustion if not handled properly.

GetAsync: The GetAsync method sends a GET request to the specified URL.

EnsureSuccessStatusCode: This method throws an exception if the HTTP response is not successful.

ReadAsStringAsync: This method reads the response content as a string.


Running this code and below is output.

I added both application in same solution so need to need to set startup as both projects.


Output, we can see both application running and we can see output in Console client along with browser.


We have learnt how to read rest api data using console application using httpclient 

we already have article for best usage of httpclient 

https://letsupdateskills.com/article/tips-and-tricks-for-http-client-in-net-core


Happy coding

line

Copyrights © 2024 letsupdateskills All rights reserved