C#,.net code and steps to get data from rest API

PATEL Prashant Kumar 20 Reputation points
2023-08-11T06:59:46.8666667+00:00

Hi,
Hope you are dong well !
I need help on below question.
I need to C#,.net code and steps to get data from any rest api?
we can get data from post man tool, but i want to do this with the code, which I can execute and get the data from required api.

Let me know if any further clarification is required.

Thanks & regards
Prashant

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,382 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,624 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
317 questions
{count} votes

2 answers

Sort by: Most helpful
  1. P a u l 10,496 Reputation points
    2023-08-11T09:20:03.7933333+00:00

    I would just have a read of this article as it goes through this topic exhaustively:

    https://video2.skills-academy.com/en-us/dotnet/fundamentals/networking/http/httpclient

    Basically it involves creating a HttpClient instance:

    private static HttpClient sharedClient = new()
    {
        BaseAddress = new Uri("https://jsonplaceholder.typicode.com"),
    };
    

    All requests made with this sharedClient will be relative to that BaseAddress.

    Then depending on the HTTP method the API endpoint requires, you can just copy the boilerplate from these sections. For example, for a HTTP GET request you can refer to this:

    https://video2.skills-academy.com/en-us/dotnet/fundamentals/networking/http/httpclient#http-get

    static async Task GetAsync(HttpClient httpClient)
    {
        using HttpResponseMessage response = await httpClient.GetAsync("todos/3");
        
        response.EnsureSuccessStatusCode()
            .WriteRequestToConsole();
        
        var jsonResponse = await response.Content.ReadAsStringAsync();
        Console.WriteLine($"{jsonResponse}\n");
    }
    

    The reason why sharedClient is static in this example (one instance) of it is because reusing a HttpClient allows you to utilise sockets on your server much more efficiently.

    If you're creating thousands of requests every few minutes you will definitely want to reuse your HttpClient instance.

    If you'd prefer not to have to static instance in your application then there's the concept of an IHttpClientFactory that abstracts this away, such that you just need to ask the factory for a new HttpClient and it'll create/repurpose an existing instance:

    https://video2.skills-academy.com/en-us/dotnet/core/extensions/httpclient-factory#basic-usage

    0 comments No comments

  2. Lan Huang-MSFT 28,836 Reputation points Microsoft Vendor
    2023-08-15T06:13:31.3833333+00:00

    Hi @PATEL Prashant Kumar,

    what will be the change in the code or process , if I want first to generate a token from post method and then want to use that token in get request for same API?

    If you want to generate a token through the post method, you need to add the following code to the code provided earlier. You can add tokens to your httpclinet using the AuthenticationHeaderValue class.

                    var user = "username";
                    var password = "password";
                    var base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{user}:{password}"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64String);
    

    and how to do this using visual studio?

    You want to use it in Visual Studio, but we're not sure exactly how you want to use it. I think you can create Asp.Net Core Mvc project to call API.The following is an example I wrote in the Create method for your reference.

    C# REST: HttpRequest Headers. "Authorization", $"Bearer..." Need to add AppId and Token

    How to add Bearer token to a request in ASP.NET CORE

     [HttpPost]
            public async Task<IActionResult> Create( Employee employee)
            {    
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri("https://localhost:7146/");
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.Accept.Clear();
                //Set Basic Auth
                var user = "username";
                var password = "password";
                var base64String = Convert.ToBase64String(Encoding.ASCII.GetBytes($"{user}:{password}"));
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64String);
                HttpResponseMessage response = await client.PostAsJsonAsync("api/Member", employee);
                if (response.IsSuccessStatusCode == true)
                {
                    var EmpResponse = response.Content.ReadAsStringAsync().Result;             
                }
                return View();
               
            }
    

    User's image

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.