Consuming REST APIs with C#

In this tutorial, we will cover the basics of consuming REST APIs using C#. Representational State of Resource (REST) is an architectural style for designing networked applications. It relies on a stateless, client-server architecture where the server provides resources to the client.

Introduction to HttpClient

To consume a REST API in C#, we use the HttpClient class. This class provides a flexible way to send HTTP requests and receive HTTP responses from a URI identified by a string.

Creating an Instance of HttpClient

Here’s how you can create an instance of HttpClient:

using System.Net.Http;

// Create a new instance of HttpClient
var client = new HttpClient();

It is recommended to reuse instances of HttpClient throughout the life of your application. This helps improve performance by reducing the overhead of creating and disposing of multiple instances.

Configuring the Base Address

You can set the base address for all requests made using the HttpClient instance:

// Set the base address
client.BaseAddress = new Uri("https://sub.domain.com/");

Adding Headers

You can add headers to your HTTP requests. For example, you might need to specify the format of the data you’re sending or receiving:

// Add an Accept header for JSON format
client.DefaultRequestHeaders.Accept.Add(
    new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

Sending GET Requests

To send a GET request, use the GetAsync method:

// Send a GET request
var response = await client.GetAsync("objects.json?api_key=123");

Handling Responses

After sending a request, you can check if the response was successful by checking the IsSuccessStatusCode property:

if (response.IsSuccessStatusCode)
{
    // Parse the response body
    var dataObjects = await response.Content.ReadAsAsync<IEnumerable<DataObject>>();
    foreach (var d in dataObjects)
    {
        Console.WriteLine(d.Name);
    }
}
else
{
    Console.WriteLine($"{(int)response.StatusCode} ({response.ReasonPhrase})");
}

Sending POST Requests

To send a POST request, use the PostAsync method:

// Create a new DataObject instance
var dataObject = new DataObject { Name = "Name" };

// Serialize the object to JSON
var json = Newtonsoft.Json.JsonConvert.SerializeObject(dataObject);

// Send a POST request
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("objects.json", content);

Best Practices

  • Always reuse instances of HttpClient throughout the life of your application.
  • Use async/await to avoid blocking calls and improve performance.
  • Handle responses properly by checking for success status codes and parsing the response body.

By following these guidelines, you can effectively consume REST APIs using C# and build robust, scalable applications.

Full Example

Here’s a full example that demonstrates how to use HttpClient to send GET and POST requests:

using System;
using System.Net.Http;
using System.Threading.Tasks;

public class DataObject
{
    public string Name { get; set; }
}

class Program
{
    static async Task Main(string[] args)
    {
        var client = new HttpClient();
        client.BaseAddress = new Uri("https://sub.domain.com/");
        client.DefaultRequestHeaders.Accept.Add(
            new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

        // Send a GET request
        var response = await client.GetAsync("objects.json?api_key=123");
        if (response.IsSuccessStatusCode)
        {
            var dataObjects = await response.Content.ReadAsAsync<IEnumerable<DataObject>>();
            foreach (var d in dataObjects)
            {
                Console.WriteLine(d.Name);
            }
        }
        else
        {
            Console.WriteLine($"{(int)response.StatusCode} ({response.ReasonPhrase})");
        }

        // Send a POST request
        var dataObject = new DataObject { Name = "Name" };
        var json = Newtonsoft.Json.JsonConvert.SerializeObject(dataObject);
        var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
        response = await client.PostAsync("objects.json", content);

        if (response.IsSuccessStatusCode)
        {
            Console.WriteLine("Data object created successfully.");
        }
        else
        {
            Console.WriteLine($"{(int)response.StatusCode} ({response.ReasonPhrase})");
        }
    }
}

This example demonstrates how to use HttpClient to send GET and POST requests, handle responses, and parse the response body.

Leave a Reply

Your email address will not be published. Required fields are marked *