Skip to content
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 response

Explanation

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