C# Example: Making a GET request to a REST API and processing the response - Biz Tech

C# Example: Making a GET request to a REST API and processing the response

Listen
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;

class Program
{
    static async Task Main(string[] args)
    {
        string url = "https://api.github.com/users/octocat";

        using (HttpClient client = new HttpClient())
        {
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync(url);

            if (response.IsSuccessStatusCode)
            {
                string responseBody = await response.Content.ReadAsStringAsync();

                GitHubUser user = JsonConvert.DeserializeObject<GitHubUser>(responseBody);

                Console.WriteLine(user.name + " - " + user.bio);
            }
            else
            {
                Console.WriteLine("Error: " + response.ReasonPhrase);
            }
        }
    }
}

class GitHubUser
{
    public string name { get; set; }
    public string bio { get; set; }
}
 

This example makes a GET request to the GitHub API to retrieve information about the octocat user, processes the response, and outputs the user’s name and bio to the console. The following steps are performed:

  1. Define a string variable url with the URL of the GitHub API endpoint for the octocat user.
  2. Use the HttpClient class to create a new HTTP client object.
  3. Set the Accept header of the client object to indicate that we want to receive JSON data.
  4. Use the GetAsync() method of the client object to send a GET request to the API endpoint and retrieve a HttpResponseMessage object.
  5. Check if the response was successful using the IsSuccessStatusCode property of the HttpResponseMessage object.
  6. If the response was successful, use the ReadAsStringAsync() method of the HttpContent object returned by the Content property of the HttpResponseMessage object to retrieve the response body as a string.
  7. Use the JsonConvert.DeserializeObject() method to deserialize the JSON response into a GitHubUser object.
  8. Output the name and bio properties of the GitHubUser object to the console using Console.WriteLine().
  9. If the response was not successful, output an error message to the console using Console.WriteLine().

Note that there are many other types of APIs you can work with, such as SOAP APIs and OAuth APIs, as well as many other types of operations you can perform, such as making POST requests, sending headers, and handling errors. This example is just one possible multi-step process for working with APIs.