Hackforge Academy

Category: python

What is an API Gateway?

Published on 22 Aug 2026

Explanation

An API Gateway is a single entry point between clients and multiple backend microservices. Instead of clients directly calling User, Product, Order, and Payment services, they send requests to the API Gateway. The gateway then routes each request to the appropriate service. It can also handle common responsibilities such as authentication, authorization, request logging, rate limiting, CORS, and response transformation. In a Python microservices architecture, an API Gateway can be implemented using FastAPI or a dedicated reverse proxy such as Nginx.

Code:

# Client
#    |
#    v
# API Gateway
#    |
#    +------> User Service
#    |
#    +------> Product Service
#    |
#    +------> Order Service
#    |
#    +------> Payment Service

Explanation

FastAPI can be used to create a simple API Gateway that receives requests from clients and forwards them to backend services. The gateway can expose routes such as /users, /products, and /orders while hiding the internal service URLs from clients. HTTPX can be used to communicate with the backend services. This approach is useful for learning and for lightweight systems, while larger production environments may use dedicated API gateways or reverse proxies.

Code:

from fastapi import FastAPI
import httpx

app = FastAPI(title='API Gateway')

USER_SERVICE = 'http://localhost:8001'
PRODUCT_SERVICE = 'http://localhost:8002'


@app.get('/users')
async def get_users():
    async with httpx.AsyncClient() as client:
        response = await client.get(
            f'{USER_SERVICE}/users'
        )

    return response.json()


@app.get('/products')
async def get_products():
    async with httpx.AsyncClient() as client:
        response = await client.get(
            f'{PRODUCT_SERVICE}/products'
        )

    return response.json()


# Run:
# uvicorn gateway:app --port 8000

Explanation

Routing is one of the primary responsibilities of an API Gateway. The gateway examines the incoming URL and forwards the request to the appropriate backend service. For example, /users requests can be routed to the User Service, /products requests to the Product Service, and /orders requests to the Order Service. This allows clients to communicate with one public API while individual services remain internally separated.

Code:

from fastapi import FastAPI
import httpx

app = FastAPI()

SERVICES = {
    'users': 'http://localhost:8001',
    'products': 'http://localhost:8002',
    'orders': 'http://localhost:8003'
}


@app.get('/{service}/{item_id}')
async def route_request(service: str, item_id: int):
    service_url = SERVICES.get(service)

    if not service_url:
        return {'error': 'Service not found'}

    async with httpx.AsyncClient() as client:
        response = await client.get(
            f'{service_url}/{service}/{item_id}',
            timeout=5.0
        )

    return response.json()

Explanation

An API Gateway can centralize cross-cutting concerns that would otherwise need to be implemented in every microservice. Authentication is a common example: the gateway can validate a JWT token before forwarding a request to the backend service. It can also apply authorization rules, rate limits, CORS policies, request logging, and request IDs. Centralizing these responsibilities reduces duplicated code, although sensitive business authorization should still be enforced by the individual services when necessary.

Code:

from fastapi import FastAPI, Header, HTTPException

app = FastAPI()


@app.get('/products')
def get_products(authorization: str | None = Header(default=None)):
    if not authorization:
        raise HTTPException(
            status_code=401,
            detail='Authorization token required'
        )

    # Token validation would happen here.
    # After successful validation,
    # the request can be forwarded to Product Service.

    return {
        'message': 'Request authorized'
    }

Explanation

A production microservices architecture commonly places an API Gateway in front of multiple independent services. Clients communicate only with the gateway, while the gateway routes requests to internal services. The gateway can provide authentication, rate limiting, logging, and routing, while each microservice handles its own business logic and data. For larger systems, tools such as Nginx, Traefik, Kong, or cloud-managed API gateways may be used instead of implementing every gateway feature directly in FastAPI.

Code:

# Production-style architecture
#
#                    Web / Mobile Client
#                            |
#                            v
#                    +---------------+
#                    |  API Gateway  |
#                    +---------------+
#                      /      |      \
#                     /       |       \
#                    v        v        v
#              User Service Product   Order Service
#                              Service      |
#                                          v
#                                   Payment Service
#
# API Gateway responsibilities:
# - Routing
# - Authentication
# - Authorization
# - Rate Limiting
# - CORS
# - Logging
# - Request ID / Tracing

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community