I would just have a read of this article as it goes through this topic exhaustively:
https://video2.skills-academy.com/en-us/dotnet/fundamentals/networking/http/httpclient
Basically it involves creating a HttpClient
instance:
private static HttpClient sharedClient = new()
{
BaseAddress = new Uri("https://jsonplaceholder.typicode.com"),
};
All requests made with this sharedClient
will be relative to that BaseAddress
.
Then depending on the HTTP method the API endpoint requires, you can just copy the boilerplate from these sections. For example, for a HTTP GET request you can refer to this:
https://video2.skills-academy.com/en-us/dotnet/fundamentals/networking/http/httpclient#http-get
static async Task GetAsync(HttpClient httpClient)
{
using HttpResponseMessage response = await httpClient.GetAsync("todos/3");
response.EnsureSuccessStatusCode()
.WriteRequestToConsole();
var jsonResponse = await response.Content.ReadAsStringAsync();
Console.WriteLine($"{jsonResponse}\n");
}
The reason why sharedClient
is static in this example (one instance) of it is because reusing a HttpClient
allows you to utilise sockets on your server much more efficiently.
If you're creating thousands of requests every few minutes you will definitely want to reuse your HttpClient
instance.
If you'd prefer not to have to static instance in your application then there's the concept of an IHttpClientFactory
that abstracts this away, such that you just need to ask the factory for a new HttpClient
and it'll create/repurpose an existing instance:
https://video2.skills-academy.com/en-us/dotnet/core/extensions/httpclient-factory#basic-usage