FastAPI
Middleware
Add CORS, timing, and custom middleware.
By EZ4Code Team
middlewarecors
Code
import time
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://example.com"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@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 responseExplanation
Middleware wraps every request before route matching and every response after the handler. CORSMiddleware injects the headers browsers expect for cross-origin requests. A function-based middleware receives the request and a call_next callable, allowing pre- and post-processing around the handler.
More FastAPI Snippets
Path Parameters
Capture typed path segments with validation.
Query Parameters
Parse query strings with defaults and validation.
Pydantic Request Body
Validate JSON bodies with Pydantic models.
Dependency Injection
Share logic via Depends and yield-based dependencies.
Response Model
Shape and filter responses with response_model.
JWT Auth
Issue and verify JSON Web Tokens with OAuth2.