9. Middleware & Request Lifecycle
Middleware functions run before every request and can modify the request, the response, or execute code before and after the request is processed. They are perfect for cross-cutting concerns like logging, CORS, rate limiting, and request timing. To test these examples, save to main.py and run uvicorn main:app --reload.
What is Middleware?
A middleware is a function that executes for every request in a specific order. It can inspect and modify the request before it reaches your endpoint, execute code after your endpoint processes the request, intercept the request and return a response early, or add headers to the response.
from fastapi import FastAPI, Request import time app = FastAPI() @app.middleware("http") async def add_process_time_header(request: Request, call_next): start_time = time.perf_counter() response = await call_next(request) process_time = time.perf_counter() - start_time response.headers["X-Process-Time"] = str(process_time) return response @app.get("/") def root(): return {"message": "Hello"}
Logging Middleware
Log every request with method, path, status code, and execution time. This is essential for debugging and monitoring.
from fastapi import FastAPI, Request import time import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) app = FastAPI() @app.middleware("http") async def log_requests(request: Request, call_next): start_time = time.perf_counter() logger.info(f"Request: {request.method} {request.url.path}") response = await call_next(request) process_time = time.perf_counter() - start_time logger.info(f"Response: {request.method} {request.url.path} Status: {response.status_code} Duration: {process_time:.4f}s") return response @app.get("/") def root(): return {"message": "Hello"}
Request ID Middleware
Add a unique request ID to every request for tracing across logs. Clients can send their own ID via header, or the server generates one.
from fastapi import FastAPI, Request from uuid import uuid4 app = FastAPI() @app.middleware("http") async def request_id_middleware(request: Request, call_next): request_id = request.headers.get("X-Request-ID", str(uuid4())) request.state.request_id = request_id response = await call_next(request) response.headers["X-Request-ID"] = request_id return response @app.get("/test") async def test(request: Request): request_id = request.state.request_id return {"request_id": request_id}
Built-in Middleware: CORS
Cross-Origin Resource Sharing (CORS) is essential when your API is called from a different domain (like a React app on localhost:3000 calling your API on localhost:8000).
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() origins = [ "http://localhost:3000", "https://myfrontend.com", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.get("/") def root(): return {"message": "Hello"}
Rate Limiting Middleware
Protect your API from abuse by limiting how many requests a client can make in a given time window.
from fastapi import FastAPI, Request, HTTPException from collections import defaultdict import time app = FastAPI() request_counts = defaultdict(list) @app.middleware("http") async def rate_limit_middleware(request: Request, call_next): client_ip = request.client.host now = time.time() window = 60 max_requests = 60 request_counts[client_ip] = [ req_time for req_time in request_counts[client_ip] if now - req_time < window ] if len(request_counts[client_ip]) >= max_requests: raise HTTPException(status_code=429, detail="Too many requests") request_counts[client_ip].append(now) response = await call_next(request) return response
Authentication Middleware
Extract and validate authentication tokens before the request reaches your endpoints.
from fastapi import FastAPI, Request, HTTPException import jwt app = FastAPI() SECRET_KEY = "your-secret-key" ALGORITHM = "HS256" @app.middleware("http") async def auth_middleware(request: Request, call_next): public_paths = ["/docs", "/openapi.json", "/health", "/login"] if request.url.path in public_paths: return await call_next(request) auth_header = request.headers.get("Authorization") if not auth_header or not auth_header.startswith("Bearer "): raise HTTPException(status_code=401, detail="Missing or invalid token") token = auth_header.split(" ")[1] try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) request.state.user_id = payload.get("sub") except jwt.InvalidTokenError: raise HTTPException(status_code=401, detail="Invalid token") response = await call_next(request) return response
Knowledge Check
Ready to test your understanding of 9. Middleware & Request Lifecycle?