How to Use HttpClient to GET JSON from API endpoint in C#

By FoxLearn 1/9/2025 2:07:44 AM   150
Why not create a method that can make a GET request to an API and directly return the response as an object?

Most APIs return JSON data anyway, so this approach is both convenient and efficient.

CREATE A MODEL CLASS

For instance, imagine we have a Joke API that returns a random joke in the following JSON format:

{
  "joke": "Why don't skeletons fight each other? They don't have the guts.",
  "id": 123
}

We’ll define a model class to represent the data structure:

public class JokeModel
{
    public string Joke { get; set; }
    public int Id { get; set; }
}

CREATE AN HttpClientRepository

Now let’s set up a class that uses HttpClient to make the GET request and return the result as a deserialized object.

using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace MyCode
{
    public class HttpClientRepository
    {
        private IHttpClientFactory _httpClientFactory;

        public HttpClientRepository(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public async Task<T?> GetAsync<T>(string url)
        {
            var client = _httpClientFactory.CreateClient("HttpClient");
            var response = await client.GetAsync(url);
            if (!response.IsSuccessStatusCode)
                throw new Exception($"{response.StatusCode}: {response.ReasonPhrase}");

            var responseObject = await response.Content.ReadFromJsonAsync<T>();
            return responseObject;
        }
    }
}

The GetAsync method is generic, allowing it to return any type of object (T) that matches the JSON structure from the API. This method handles deserialization automatically, making it very flexible for different API responses.

CONFIGURE HttpClient and USE THE REPOSITORY

In your Program.cs, configure the HttpClient and inject the HttpClientRepository:

builder.Services.AddHttpClient("HttpClient");
builder.Services.AddSingleton<HttpClientRepository>();

To use the repository and retrieve a random joke from the Joke API, you can call the GetAsync method as follows:

public async Task<string?> GetRandomJokeAsync()
{
    JokeModel? joke = await _httpRepository.GetAsync<JokeModel>("https://api.jokes.com/random");
    return joke?.Joke;
}

While asynchronous programming is the better practice, if you prefer to use a synchronous approach, you can call the Result property:

public string? GetRandomJoke()
{
    JokeModel? joke = _httpRepository.GetAsync<JokeModel>("https://api.jokes.com/random").Result;
    return joke?.Joke;
}

Using .Result can cause issues in certain situations (like deadlocks), so it’s highly recommended to use async/await when possible.