What is API Gateway pattern?

4 minintermediatemicroservicesAPI-gatewayarchitecture

Quick Answer

The API Gateway is a single entry point in front of microservices that routes requests, aggregates responses, and centralizes cross-cutting concerns like authentication, rate limiting, caching, and TLS termination. It shields clients from internal service topology and reduces chatty client-to-service calls. The trade-off is that it can become a bottleneck or single point of failure if not scaled and kept thin.

Detailed Answer

The API Gateway pattern provides a single entry point for all clients to access microservices. It acts as a reverse proxy, routing requests to appropriate microservices and aggregating responses.

Key Responsibilities:

  • Request routing and composition
  • Authentication and authorization
  • Rate limiting and throttling
  • Load balancing
  • Protocol translation
  • Response aggregation
  • Caching

Implementation with Ocelot in .NET Core:

// Install: Install-Package Ocelot

// ocelot.json configuration
{
  "Routes": [
    {
      "DownstreamPathTemplate": "/api/products/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "product-service",
          "Port": 5001
        }
      ],
      "UpstreamPathTemplate": "/products/{everything}",
      "UpstreamHttpMethod": [ "Get", "Post", "Put", "Delete" ]
    },
    {
      "DownstreamPathTemplate": "/api/orders/{everything}",
      "DownstreamScheme": "http",
      "DownstreamHostAndPorts": [
        {
          "Host": "order-service",
          "Port": 5002
        }
      ],
      "UpstreamPathTemplate": "/orders/{everything}",
      "UpstreamHttpMethod": [ "Get", "Post" ],
      "AuthenticationOptions": {
        "AuthenticationProviderKey": "Bearer"
      }
    }
  ],
  "GlobalConfiguration": {
    "BaseUrl": "http://localhost:5000"
  }
}

// Program.cs
public class Program
{
    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);
        
        builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
        builder.Services.AddOcelot(builder.Configuration);
        
        var app = builder.Build();
        app.UseOcelot().Wait();
        app.Run();
    }
}

Custom API Gateway:

[ApiController]
[Route("api/gateway")]
public class ApiGatewayController : ControllerBase
{
    private readonly IHttpClientFactory _httpClientFactory;
    
    public ApiGatewayController(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }
    
    [HttpGet("product/{id}/details")]
    public async Task GetProductDetails(int id)
    {
        var productClient = _httpClientFactory.CreateClient("ProductService");
        var inventoryClient = _httpClientFactory.CreateClient("InventoryService");
        var reviewClient = _httpClientFactory.CreateClient("ReviewService");
        
        // Aggregate responses from multiple services
        var productTask = productClient.GetFromJsonAsync($"/api/products/{id}");
        var inventoryTask = inventoryClient.GetFromJsonAsync($"/api/inventory/{id}");
        var reviewsTask = reviewClient.GetFromJsonAsync<List>($"/api/reviews/product/{id}");
        
        await Task.WhenAll(productTask, inventoryTask, reviewsTask);
        
        return Ok(new {
            Product = productTask.Result,
            Inventory = inventoryTask.Result,
            Reviews = reviewsTask.Result
        });
    }
}

Related Resources