Dofactory.com
Dofactory.com

How to call a REST API using C#

Use HttpClient to make REST API calls and other type of requests.
Below is the code for making a request.


static void Main(string[] args)
{
    using var client = new HttpClient();
    client.BaseAddress = new Uri(url);

    // Add an Accept header for JSON format.

    client.DefaultRequestHeaders.Accept.Add(
       new MediaTypeWithQualityHeaderValue("application/json"));

    // Get data response

    var response = client.GetAsync(urlParameters).Result;  
    if (response.IsSuccessStatusCode)
    {
        // Parse the response body

        var dataObjects = response.Content
                       .ReadAsAsync<IEnumerable<DataObject>>().Result;  
        foreach (var d in dataObjects)
        {
            Console.WriteLine("{0}", d.Name);
        }
    }
    else
    {
        Console.WriteLine("{0} ({1})", (int)response.StatusCode,
                      response.ReasonPhrase);
    }
}


Jack Poorte
Jack Poorte
Last updated on Sep 30, 2023



Stay Inspired!
Join other developers and designers who have already signed up for our mailing list.
Terms     Privacy     Cookies       Do Not Sell       Licensing      
Made with    in Austin, Texas.  - vsn 44.0.0
© Data & Object Factory, LLC.