DEV Community

Kaushikcoderpy
Kaushikcoderpy

Posted on • Originally published at logicandlegacy.blogspot.com

API Middlewares — The Bouncer at the Door (FastAPI & ASGI) (2026)

Understanding Middleware in Backend Architecture

When building robust backend systems, it's essential to consider the security and integrity of the data being exchanged. One crucial aspect of achieving this is by implementing middleware. In this context, middleware refers to a layer of code that intercepts every incoming request to the application, inspecting it before deciding whether to pass it through to the core logic or reject it.

The Onion Architecture Analogy

Imagine your web server as an onion, with multiple layers. The core of the onion represents your business logic, such as fetching user data or processing orders. The outer layers are where the middleware resides. Each incoming request must pass through these outer layers before reaching the core. This design ensures that security checks and other essential processes are applied uniformly across all requests.

Inbound and Outbound Processing

Middleware functions can be thought of as having two phases: inbound and outbound.

  • Inbound Phase: When a request first arrives, the middleware checks it against certain criteria, such as the client's IP address or the presence of a valid token. If the request passes these checks, it is allowed to proceed to the next layer.
  • The Handoff: After passing the inbound checks, the request is yielded to the application's router, which directs it to the appropriate endpoint. The endpoint processes the request and generates a response.
  • Outbound Phase: As the response is sent back, the middleware catches it and can modify it if necessary. This might involve adding security headers or logging the response time.

Implementing Middleware with FastAPI and Starlette

In a production environment, you wouldn't typically write raw network intercepts. Instead, you would use the tools provided by the ASGI (Asynchronous Server Gateway Interface) specification. For FastAPI applications, you can build middleware by inheriting from Starlette's BaseHTTPMiddleware. This approach allows you to create a "bouncer" that protects your application from unwanted requests.

from fastapi import FastAPI, Request, Response
from starlette.middleware.base import BaseHTTPMiddleware

app = FastAPI()
BLOCKED_IPS = ["192.168.1.50"]

class SecurityBouncer(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        client_ip = request.client.host
        if client_ip in BLOCKED_IPS:
            return Response(content="Banned", status_code=403)
        response = await call_next(request)
        response.headers["X-Frame-Options"] = "DENY"
        return response

app.add_middleware(SecurityBouncer)
Enter fullscreen mode Exit fullscreen mode

This example demonstrates how to create a simple middleware that checks the client's IP address and adds a security header to the response.

The Importance of Middleware Order

The order in which middleware is added to an application can significantly impact its behavior. Middleware functions stack on top of each other, with the last one added being the first to execute. This means you should carefully consider the order in which you add middleware to ensure that your application's security and functionality are not compromised.

Best Practices for Middleware Development

When developing middleware, it's crucial to keep in mind the following best practices:

  • Keep it Fast: Middleware should execute quickly to avoid slowing down the entire application.
  • Avoid Blocking Operations: Synchronous operations within middleware can block the execution of other requests, leading to performance issues.
  • Test Thoroughly: Ensure that your middleware is thoroughly tested to catch any potential issues before they reach production.

By following these guidelines and understanding the role of middleware in your backend architecture, you can build more secure, scalable, and maintainable applications.

Top comments (0)