Skip to content

Call another API using HttpClient

In .NET Framework, we used to use WebClient or HttpWebRequest to call another API.

.NET Core introduced HttpClient which is modern and asynchronous.

For sample API, we can call https://uselessfacts.jsph.pl/.

In appsettings.Development.json, add

json
"Api": {
    "Fact": "https://uselessfacts.jsph.pl/api/v2/facts/random"
  }


Add a folder Apis and add FactResponse.cs

csharp
public class FactResponse
{
    public string Id { get; set; }
    public string Text { get; set; }
}


In Apis folder, add FactApi.cs

csharp
public class FactApi : IFactApi
{
    private readonly ILogger<FactApi> _logger;
    private readonly HttpClient _httpClient;
    private readonly string _baseUrl;

    public FactApi(ILogger<FactApi> logger, HttpClient httpClient, IConfiguration configuration)
    {
        _logger = logger;
        _httpClient = httpClient;
        _baseUrl = configuration.Get<AppSettings>().Api.Fact;
    }

    public async Task<string> GetFact()
    {
        var httpRequest = new HttpRequestMessage(HttpMethod.Get, _baseUrl);

        var response = await _httpClient.SendAsync(httpRequest);
        if (response is not { StatusCode: HttpStatusCode.OK })
        {
            var errorResponse = await response.Content.ReadAsStringAsync();
            _logger.LogError("FactApi.GetFact - Could not get fact, status={@status}, response={@response}",
                response.StatusCode, errorResponse);
            throw new ApiException(errorResponse);
        }
        
        var fact = await response.Content.ReadAsAsync<FactResponse>();
        return fact.Text;
    }
}


In DependencyConfigurator.cs

csharp
public static void RegisterDependencies(this WebApplicationBuilder builder)
{
    RegisterRepos(builder);
    RegisterServices(builder);
    RegisterApis(builder); //add this
    RegisterHelpers(builder);
}

private static void RegisterApis(WebApplicationBuilder builder)
{
    builder.Services.AddHttpClient<IFactApi, FactApi>();
}


In Controllers folder, add FactController.cs

csharp
[ApiController]
[Route("[controller]")]
public class FactController : Controller
{
    private readonly ILogger<FactController> _logger;
    private readonly IFactApi _factApi;

    public FactController(ILogger<FactController> logger, IFactApi factApi)
    {
        _logger = logger;
        _factApi = factApi;
    }

    [HttpGet]
    public async Task<IActionResult> Get()
    {
        var fact = await _factApi.GetFact();
        return Ok(fact);
    }
}


Test the API

GET {{Library_HostAddress}}/fact/
Content-Type: application/json

alt text

Released under the MIT License.