How to Use HttpClient to GET JSON from API endpoint in C#
By Tan Lee Published on Jan 09, 2025 464
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:
1 2 3 4 |
{ "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:
1 2 3 4 5 |
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.
For example, c# use HttpClient to get json from api endpoint
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
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
:
1 2 |
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:
1 2 3 4 5 |
public async Task< string ?> GetRandomJokeAsync() { return joke?.Joke; } |
While asynchronous programming is the better practice, if you prefer to use a synchronous approach, you can call the Result
property:
1 2 3 4 5 |
public string ? GetRandomJoke() { return joke?.Joke; } |
Using .Result
can cause issues in certain situations (like deadlocks), so it’s highly recommended to use async
/await
when possible.