← Back to Tutorials

32. Middleware

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

app = FastAPI()

# Custom middleware class
class ProcessTimeMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        start = time.time()
        response = await call_next(request)
        process_time = time.time() - start
        response.headers["X-Process-Time"] = str(process_time)
        return response

app.add_middleware(ProcessTimeMiddleware)

# Simple middleware using @app.middleware
@app.middleware("http")
async def add_custom_header(request: Request, call_next):
    response = await call_next(request)
    response.headers["X-Powered-By"] = "FastAPI"
    return response

# Authentication middleware
@app.middleware("http")
async def authenticate(request: Request, call_next):
    if request.url.path.startswith("/admin"):
        token = request.headers.get("Authorization")
        if not token:
            return JSONResponse(
                {"error": "Not authenticated"},
                status_code=401
            )
    response = await call_next(request)
    return response
✏️ Exercise: Create middleware that logs each request's method, path, and duration. Add a middleware that blocks requests from specific IPs.