← Back to FastAPI, page 2

fastapi-0023 · Medium mid

How do you write middleware in FastAPI, and what are the trade-offs between @app.middleware('http') and pure ASGI middleware?

@app.middleware("http") (Starlette's BaseHTTPMiddleware) receives the request and a call_next function, runs code before and after the endpoint, and can modify the response; it is simple and fine for headers and timing. Pure ASGI middleware is a class that wraps the app's (scope, receive, send) interface; it is more work but avoids BaseHTTPMiddleware's overhead and limitations with streaming responses and context variables. Middleware runs for every request, including 404s, in the reverse order of being added.

Full answer

Middleware wraps the whole application. Each request passes through it before reaching routing and the endpoint, and each response passes back through it.

Simple style:

python
@app.middleware("http")
async def add_timing(request: Request, call_next):
    start = time.perf_counter()
    response = await call_next(request)
    response.headers["X-Process-Time"] = f"{time.perf_counter() - start:.4f}"
    return response

Or as a class: class Timing(BaseHTTPMiddleware) with dispatch(self, request, call_next), added via app.add_middleware(Timing).

Order: add_middleware wraps the current stack, so the last added middleware is the outermost and runs first on the request.

Pure ASGI middleware:

python
class RequestID:
    def __init__(self, app): self.app = app
    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            return await self.app(scope, receive, send)
        async def send_wrapper(message):
            if message["type"] == "http.response.start":
                message["headers"].append((b"x-request-id", ...))
            await send(message)
        await self.app(scope, receive, send_wrapper)

Why choose pure ASGI:

  • Less overhead per request (BaseHTTPMiddleware wraps streams and tasks).
  • Works naturally with streaming responses and WebSockets (BaseHTTPMiddleware only handles HTTP).
  • Context variables set inside it are visible to the endpoint.

Uses for middleware: request IDs, timing and logging, security headers, CORS, GZip, trusted host checks, HTTPS redirect.

When not to use middleware: logic that needs route information or applies to some routes only fits better in dependencies. Authentication is usually a dependency so it appears in OpenAPI and can vary per route.

Exceptions: unhandled exceptions from the endpoint propagate through call_next. Starlette's ServerErrorMiddleware is always outermost, so a 500 response is still produced.

python
import itertools
import time

from fastapi import FastAPI, Request
from fastapi.testclient import TestClient

app = FastAPI()
counter = itertools.count(1)


@app.middleware("http")
async def timing(request: Request, call_next):
    start = time.perf_counter()
    response = await call_next(request)
    response.headers["X-Process-Time"] = f"{time.perf_counter() - start:.4f}"
    return response


class RequestIDMiddleware:
    """Pure ASGI middleware: adds X-Request-ID without wrapping the response body."""

    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] != "http":
            await self.app(scope, receive, send)
            return
        request_id = f"req-{next(counter)}".encode()
        scope.setdefault("state", {})["request_id"] = request_id.decode()

        async def send_with_id(message):
            if message["type"] == "http.response.start":
                message.setdefault("headers", []).append((b"x-request-id", request_id))
            await send(message)

        await self.app(scope, receive, send_with_id)


app.add_middleware(RequestIDMiddleware)


@app.get("/marks")
def marks(request: Request):
    return {"request_id": request.state.request_id}


c = TestClient(app)
r = c.get("/marks")
print(r.json(), r.headers["x-request-id"], "x-process-time" in r.headers)
r = c.get("/missing")
print(r.status_code, r.headers["x-request-id"], "x-process-time" in r.headers)

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. X-Process-Time varies per run, so the script only checks that the header exists. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'request_id': 'req-1'} req-1 True 404 req-2 True

Key points

  • @app.middleware('http') is simple: request, call_next, response
  • Last added middleware runs first
  • Pure ASGI middleware has less overhead and handles streaming
  • Middleware runs on every request, even 404s
  • Per-route logic like auth fits better in dependencies

Common mistakes

  • Doing authentication in middleware so it is invisible in OpenAPI and hard to vary per route
  • Reading the request body in BaseHTTPMiddleware and breaking the endpoint's access to it
  • Adding middleware in the wrong order, for example CORS inside another middleware that returns early
  • Doing slow work in middleware that runs on every request

Follow-ups

  • Why might BaseHTTPMiddleware cause problems with StreamingResponse?
  • How would you propagate a request ID into log records?
  • In which order do three added middlewares run?

Tips

  • Show both styles and say when to pick each
  • Explain the ordering rule
  • Say what should be a dependency instead