Middleware

Custom Middleware

Example

Middleware wraps every request: add headers, measure timing, log, or reject requests:

import time
from fastapi import FastAPI, Request

app = FastAPI()

@app.middleware("http")
async def add_timing_header(request: Request, call_next):
    start = time.perf_counter()
    response = await call_next(request)
    response.headers["X-Process-Time-ms"] = f"{(time.perf_counter() - start) * 1000:.0f}"
    response.headers["X-App"] = "course-api"
    return response

@app.get("/ping")
def ping():
    return {"pong": True}

Requests and responses

GET /ping
→ 200 {"pong": true}
  x-app: course-api
  x-process-time-ms: 1