Third-party API Integration in Asp.NET Core Web API

ASP.NET Core is a powerful framework for building web APIs, allowing developers to create robust and scalable applications. One of the key features of modern web development is the integration of third-party APIs, which provide access to external services and data.

Create Model

using System.Text.Json.Serialization;

namespace _1_3rdAPIIntegrationInAspNetCoreWebAPI.Models
{
    public class Product
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public decimal Price { get; set; }
        public double DiscountPercentage { get; set; }
        public double Rating { get; set; }
        public int Stock { get; set; }
        public string Brand { get; set; }
        public string Category { get; set; }
        public string Thumbnail { get; set; }
        public List<string> Images { get; set; }
    }
}

Here's a breakdown of each property.

  • ID: An integer representing the unique identifier of the product.
  • Title: A string representing the title or name of the product.
  • Description: A string representing the description or details of the product.
  • Price: A decimal representing the price of the product.
  • DiscountPercentage: A double representing the discount percentage applied to the product.
  • Rating: A double representing the rating of the product (e.g., star rating).
  • Stock: An integer representing the available quantity of the product in stock.
  • Brand: A string representing the brand or manufacturer of the product.
  • Category: A string representing the category or type of the product.
  • Thumbnail: A string representing the URL or path to the thumbnail image of the product.
  • Images: A list of strings representing the URLs or paths to additional images of the product.

Create the Interface for the Product Service

using _1_3rdAPIIntegrationInAspNetCoreWebAPI.Models;

namespace _1_3rdAPIIntegrationInAspNetCoreWebAPI.Interfaces
{
    public interface IProducts
    {
        Task<List<ProductsResponse>> GetProductsAsync();
    }
}

GetProductsAsync: This method is declared to return a Task<List<ProductsResponse>>. It indicates that implementing classes will provide functionality to asynchronously retrieve a list of products. The List<ProductsResponse> represents a collection of product responses, which likely contain information about products such as their IDs, titles, descriptions, prices, etc. The method is asynchronous, denoted by the Task return type, indicating that it can be awaited for asynchronous execution.

Create the service for the products

using _1_3rdAPIIntegrationInAspNetCoreWebAPI.Interfaces;
using _1_3rdAPIIntegrationInAspNetCoreWebAPI.Models;
using System.Net;
using System.Text.Json;

namespace _1_3rdAPIIntegrationInAspNetCoreWebAPI.Services
{
    public class ProductService : IProducts
    {
        private static readonly HttpClient httpClient;

        static ProductService()
        {
            httpClient = new HttpClient()
            {
                BaseAddress = new Uri("https://dummyjson.com/")
            };

        }

        public async Task<List<ProductsResponse>> GetProductsAsync()
        {
            try
            {
                var url = string.Format("products");
                var result = new List<ProductsResponse>();
                var response = await httpClient.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    var stringResponse = await response.Content.ReadAsStringAsync();
                    var productsResponse = JsonSerializer.Deserialize<ProductsResponse>(stringResponse, new JsonSerializerOptions()
                    {
                        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                    });

                    // Add the deserialized ProductsResponse to the result list
                    result.Add(productsResponse);
                }
                else
                {
                    if (response.StatusCode == HttpStatusCode.NotFound)
                    {
                        throw new Exception("Products not found.");
                    }
                    else
                    {
                        throw new Exception("Failed to fetch data from the server. Status code: " + response.StatusCode);
                    }
                }

                return result;

            }
            catch (HttpRequestException ex)
            {
                throw new Exception("HTTP request failed: " + ex.Message);
            }
            catch (JsonException ex)
            {
                throw new Exception("JSON deserialization failed: " + ex.Message);
            }
            catch (Exception ex)
            {
                throw new Exception("An unexpected error occurred: " + ex.Message);
            }
        }
    }
}

Create the Controller for the Products

using _1_3rdAPIIntegrationInAspNetCoreWebAPI.Interfaces;
using _1_3rdAPIIntegrationInAspNetCoreWebAPI.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace _1_3rdAPIIntegrationInAspNetCoreWebAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ProductsController : ControllerBase
    {
        private readonly IProducts _productService;

        public ProductsController(IProducts productService)
        {
            _productService = productService;
        }

        [HttpGet]
        public async Task<IEnumerable<ProductsResponse>> GetProducts()
        {
            return await _productService.GetProductsAsync();
        }
    }
}

Register the Services in IOC Container

using _1_3rdAPIIntegrationInAspNetCoreWebAPI.Interfaces;
using _1_3rdAPIIntegrationInAspNetCoreWebAPI.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddSingleton<IProducts, ProductService>();

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Output

Output

GitHub Project Link: https://github.com/SardarMudassarAliKhan/1-3rdAPIIntegrationInAspNetCoreWebAPI

Conclusion

ASP.NET Core is a powerful framework for building web APIs, allowing developers to create robust and scalable applications. One of the key features of modern web development is the integration of third-party APIs, which provide access to external services and data.

Third-party API integration in ASP.NET Core Web API involves connecting your application to external APIs to leverage their functionality and data. This could include services for payment processing, social media integration, mapping and geolocation, weather data, and much more.

In this guide, we'll explore how to integrate third-party APIs into an ASP.NET Core Web API application. We'll cover topics such as.

  1. Setting up the ASP.NET Core Web API project.
  2. Exploring different methods of making HTTP requests to third-party APIs, such as using the HttpClient class or third-party libraries like RestSharp.
  3. Handling authentication and authorization for accessing protected APIs.
  4. Parsing and processing API responses, including handling different data formats like JSON or XML.
  5. Implementing error handling and retries for robust API communication.
  6. Best practices for managing API keys and secrets securely.
  7. Testing and debugging API integration code.
  8. Scaling and optimizing API requests for performance.

Now you know how to effectively integrate third-party APIs into your ASP.NET Core Web API applications, enabling you to create feature-rich and interconnected systems that leverage the power of external services. Let's get started!


Similar Articles