C# Use HttpClient to GET JSON from API endpoint

So, most API endpoints return JSON anyway, right? So why not make a method that can make a GET call to an API and return the response as an object directly?

It’s actually not that hard:

STEP 1: MAKE A MODEL CLASS

My Catfact API endpoint returns the following JSON:

{
  "fact": "All cats need taurine in their diet to avoid blindness. Cats must also have fat in their diet as they are unable to produce it on their own.",
  "length": 140
}

So my model class is equally simple:

public class CatModel
{
  public string Fact  { get; set; }
  public int Length { get; set; } 
}

STEP 2: MAKE A HTTPCLIENTREPOSITORY

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 method “GetAsync” deserializes the return value from the API endpoint to the model of a Generic Type “T“.

A Generic Type is a placeholder for a specific type that you define later. Using a Generic Type ensures that you can call this method regardless of the model returned, as long as the JSON can be deserialized to that model.

In other words: If your specific type matches the JSON returned, everything is fine.

STEP 3: HOW TO USE IT

In your Program.cs, add an IHttpClient and the HttpClientRepository:

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

To call the method is quite simple. This function returns the cat fact string:

public async Task<string?> GetCatFactAsync()
{
  CatModel? catFact = await _httpRepository.GetAsync<CatModel>("https://catfact.ninja/fact");
  return catFact?.Fact;
}

Not familiar with async coding? Don’t worry, just call the method it in the not-recommended way:

public string? GetCatFact()
{
  CatModel? catFact = _httpRepository.GetAsync<CatModel>("https://catfact.ninja/fact").Result;
  return catFact?.Fact;
}

But do yourself a favor and read up on async coding.

That’s it. You are now a HttpClient expert. Happy coding.

MORE TO READ:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, .NET Core, c#, General .NET and tagged , , , , , . Bookmark the permalink.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.