How to make GET requests to a REST API endpoint using C#

Last updated on 24th March 2023

REST (Representational State Transfer) API is a web-based architectural style that allows for communication between different software applications over HTTP, making it easier to share data and functionality across different systems and platforms. This article demonstrates how to make a simple GET request to a REST API endpoint using C# and the HttpClient class.

Making GET Requests to a REST API Endpoint

To make a GET request, you would typically create an instance of the HttpClient class, specify the endpoint URL and any query parameters, and then use the GetAsync() method to send the request and receive a response. The HttpClient class is part of the .NET Framework's System.Net.Http namespace. The following C# code prompts the user to enter a number and then makes a GET request to a REST API endpoint to retrieve information about a user having the specified number as user id.

using System.Text;
using System.Text.Json;

Console.Write("Enter a number between 1 and 10: ");
int id = Convert.ToInt32(Console.ReadLine());
User? user = await GetUserById(id);

if (user != null)
{
   Console.WriteLine(user.name); 
   Console.WriteLine(JsonSerializer.Serialize(user));
}
else
{
   Console.WriteLine("User not found");
}

/// <summary>
/// This asynchronous method sends a GET request to
/// a REST API endpoint and retrieves a user by id.
 </summary>
static async Task<User?> GetUserById(int id)
{
   try
   {
       using var client = new HttpClient();
       var url = $"https://jsonplaceholder.typicode.com/users/{id}";

       var response = await client.GetAsync(url);
       if (response.IsSuccessStatusCode)
       {
          var responseContent = await response.Content.ReadAsStringAsync();
          return JsonSerializer.Deserialize<User>(responseContent);
       }
       else
       {
          return null;
       }
   }
   catch (Exception ex)
   {
       Console.WriteLine(ex.ToString());
       return null;
   }
}

/// <summary>
/// Class that defines a user
/// </summary>
class User
{
   public int id { get; set; }
   public string name { get; set; } = string.Empty;
   public string username { get; set; } = string.Empty;
   public string email { get; set; } = string.Empty;
}

Note: This program uses Top-Level statements and therefore requires C# 10 compiler which is included with .NET 6 and later.

Program Explanation

The above code prompts the user to enter an ID and stores the input in a variable named id. The GetUserById is an asynchronous method and it is called with the id parameter. This method returns a User object or null, depending on whether the request to the REST API was successful.

Inside the GetUserById method, an instance of the HttpClient class is created using the using statement. This ensures that the client is properly disposed of when it is no longer needed.

A GET request is made to the "https://jsonplaceholder.typicode.com/users/{id}" endpoint using the GetAsync method of the HttpClient class and the result is stored in a variable named response. (Note: JSONPlaceholder is a free online REST API which provides sample data that can be used for testing and demo purposes.)

The IsSuccessStatusCode property of the response object is checked to determine if the request was successful. If it is true, the response content is read as a string using the ReadAsStringAsync method and deserialized into a User object.

The JsonSerializer.Deserialize method in the System.Text.Json namespace is used to deserialize a JSON string or stream into an instance of a specified .NET type. This method takes the response string which contains the JSON data as input, along with the type of object, which is User, to deserialize the data. The method then returns an instance of User type, populated with the data from the JSON input.

The User class is defined as a simple class with properties for the user's ID, name, username, and email.

Finally, if the User object is not null, the user's name and a serialized string of the user object is printed on the console.

Here is a sample output when you run this program.

Enter an id: 7
Kurtis Weissnat
{"id":7,"name":"Kurtis Weissnat","username":"Elwyn.Skiles","email":"Telly.Hoeger@billy.biz"}
{
  "id": 11
}

Post a comment

Comments

Nothing yet..be the first to share wisdom.