FASTAPI / 7. MIDDLEWARE, CORS & ROUTERS
Middleware, CORS & APIRouter
Cross-cutting concerns and organizing large applications
EXPLANATION
As your application grows, you need two things: middleware for cross-cutting concerns that apply to every request, and APIRouter for organizing routes into logical groups. Middleware sits between the raw HTTP server and your route handlers. Every request passes through all middleware before reaching a route, and every response passes back through them in reverse order. Common uses: • Logging request duration • Adding security headers • Rate limiting • Request ID injection for tracing • Gzip compression (built in: GZipMiddleware) CORS (Cross-Origin Resource Sharing) is the browser security policy that blocks JavaScript from one domain calling an API on another domain. When your Next.js frontend on localhost:3000 calls your FastAPI on localhost:8000, the browser sends a preflight OPTIONS request. CORS middleware responds with the right headers to allow it. CORSMiddleware settings: • allow_origins → list of allowed frontend URLs (never use ["*"] in production with credentials) • allow_credentials → True if you use cookies/auth headers • allow_methods → ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"] • allow_headers → ["*"] or specific headers like ["Authorization", "Content-Type"] APIRouter lets you split routes into separate files — like Express Router or Django URLs. You define routes on a router, then include the router in the main app with a prefix and tags. Lifespan (startup/shutdown): the modern way to run code on startup (create DB tables, connect to Redis) and shutdown (close connections). Replaces the deprecated @app.on_event decorators.
ARCHITECTURE
REQUEST FLOW WITH MIDDLEWARE:
Client
↓
Uvicorn (ASGI server)
↓
CORS Middleware ← handles preflight OPTIONS
↓
Logging Middleware ← logs request start
↓
GZip Middleware ← decompresses body
↓
Router (/api/v1)
↓
Route Handler ← your code runs
↑
(response travels back through middleware in reverse)
ROUTER FILE STRUCTURE:
app/
├── main.py ← app = FastAPI(), include routers
├── routers/
│ ├── tasks.py ← /api/v1/tasks/*
│ ├── users.py ← /api/v1/users/*
│ └── auth.py ← /auth/*
└── models.pyCODE