How to consume third party REST API from ASP.NET Core?


You have recently started working with .NET Core and have received a requirement to call an external API. You need to create a new endpoint that will consume this API on the client side. Despite attempting to follow the official Microsoft documentation on calling a Web API from a .NET client (C#), you encountered challenges along the way. After hours of struggling and searching online, you finally found a solution.

I have created an employee model with several properties to capture the results from the endpoint (https://www.quickpickdeal.com/api/Employee/GetEmployeeById?id=6), as shown in the image. Additionally, I have created a controller to serve as the final endpoint, returning information from this external API.

To call a third-party REST API from an ASP.NET Core Web API, I'd start by defining a model to represent the employee. 

Let's call it EmployeeModel and give it fields for Id, FirstName, LastName, Email, and PhoneNumber.


public class EmployeeModel
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
}
Next, I'm going create a service to handle the HTTP requests to the external API. This service would make HTTP calls to the third-party API and deserialize the response into our EmployeeModel.

public interface IExternalApiService
{
    Task<EmployeeModel> GetProductAsync(int id);
}

public class ExternalApiService : IExternalApiService
{
    private readonly HttpClient _httpClient;

    public ExternalApiService(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<EmployeeModel> GetEmployeeAsync(int id)
    {
        var response = await _httpClient.GetAsync($"https://www.quickpickdeal.com/api/Employee/{id}");

        if (response.IsSuccessStatusCode)
        {
            var employeeJson = await response.Content.ReadAsStringAsync();
            var employee = JsonSerializer.Deserialize<EmployeeModel>(employeeJson);
            return employee;
        }
        else
        {
            throw new HttpRequestException($"Failed to retrieve product. Status code: {response.StatusCode}");
        }
    }
}
Then, let's register this service in the ASP.NET Core dependency injection container.
public void ConfigureServices(IServiceCollection services)
{    
    services.AddHttpClient<IExternalApiService, ExternalApiService>();   
}
Let's inject inject the IExternalApiService in our controller and use it to call the third-party API.
[ApiController]
[Route("[controller]")]
public class EmployeeController : ControllerBase
{
    private readonly IExternalApiService _externalApiService;

    public EmployeeController(IExternalApiService externalApiService)
    {
        _externalApiService = externalApiService;
    }

    [HttpGet("Employee/{id}")]
    public async Task<IActionResult> GetEmployee(int id)
    {
        try
        {
            var employee = await _externalApiService.GetEmployeeAsync(id);
            return Ok(product);
        }
        catch (HttpRequestException ex)
        {
            return StatusCode(500, $"Error retrieving employee: {ex.Message}");
        }
    }
}