Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# HttpClient and API

I have a web application that pulls data from an API using the HttpClient class. I have a few questions.

  1. Is HttpClient optimal for getting data from API? I get a string from APi and deserialize it into an object.
  2. A new instance of HttpClient is created each time it is used (for each user). Is it best to use: using (HttpClient client = new HttpClient()) for each request?

Try to find best and optimal solution.

like image 620
Tsko Avatar asked Jun 14 '26 00:06

Tsko


1 Answers

  1. Yes, HttpClient is certainly appropriate for using web APIs and deserialization.

  2. Creating a new HttpClient for each request is not a good usage. The recommended way is to create HttpClient objects using the IHttpClientFactory interface. Here is a basic usage from MSDN:

     class TodoService
     {
         private readonly IHttpClientFactory _httpClientFactory = null!;
         private readonly ILogger<TodoService> _logger = null!;
    
         public TodoService(
             IHttpClientFactory httpClientFactory,
             ILogger<TodoService> logger) =>
             (_httpClientFactory, _logger) = (httpClientFactory, logger);
    
         public async Task<Todo[]> GetUserTodosAsync(int userId)
         {
             // Create the client
             using HttpClient client = _httpClientFactory.CreateClient();
    
             try
             {
                 // Make HTTP GET request
                 // Parse JSON response deserialize into Todo types
                 Todo[]? todos = await client.GetFromJsonAsync<Todo[]>(
                     $"https://jsonplaceholder.typicode.com/todos?userId={userId}",
                     new JsonSerializerOptions(JsonSerializerDefaults.Web));
    
                 return todos ?? Array.Empty<Todo>();
             }
             catch (Exception ex)
             {
                 _logger.LogError("Error getting something fun to say: {Error}", ex);
             }
    
             return Array.Empty<Todo>();
         }
     }
    

    }

You can refer to IHttpClientFactory with .NET and Guidelines for using HttpClient

like image 159
Mustafa Özçetin Avatar answered Jun 15 '26 16:06

Mustafa Özçetin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!