Well1AmNichtDiePerson
Established
In visual studio 2022, how to make/create Rest API client using http client in C#?
System.Net.Http namespace to your project. You can do this by adding a reference to the System.Net.Http NuGet package. Right-click on your project in Solution Explorer, select "Manage NuGet Packages," search for System.Net.Http, and install it.using System;
using System.Net.Http;
using System.Threading.Tasks;
public class ApiClient
{
private readonly HttpClient _client;
public ApiClient(string baseAddress)
{
_client = new HttpClient { BaseAddress = new Uri(baseAddress) };
}
public async Task<string> GetAsync(string endpoint)
{
HttpResponseMessage response = await _client.GetAsync(endpoint);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
ApiClient class and use it to make API requests. Here's an example of how to use the ApiClient class to make a GET request:class Program
{
static async Task Main(string[] args)
{
ApiClient apiClient = new ApiClient("https://api.example.com");
string response = await apiClient.GetAsync("/endpoint");
Console.WriteLine(response);
}
}
"https://api.example.com" with the base URL of the REST API you want to consume, and "/endpoint" with the specific endpoint you want to call.ApiClient class to include methods for other HTTP methods like POST, PUT, DELETE, etc., following a similar pattern as the GetAsync method.