FastAPI Reference
Free reference guide: FastAPI Reference
About FastAPI Reference
The FastAPI Reference is a practical cheat sheet for Python backend developers building high-performance async APIs with the FastAPI framework. It covers the six core categories used in production FastAPI services: routing with HTTP methods and path/query parameter validation, dependency injection with Depends(), Pydantic data models and field validation, middleware including CORS and trusted host configuration, OAuth2 and JWT security patterns, and background processing with BackgroundTasks, WebSocket endpoints, and StreamingResponse.
This reference is used by Python API developers, data scientists building ML model serving APIs, and backend engineers who have migrated from Flask or Django REST Framework to FastAPI. Each entry shows the exact Python decorator syntax, type annotation, and Pydantic usage pattern — from @app.get() route definitions with automatic OpenAPI documentation to class-based dependency injection for pagination and database session management.
The reference is organized into six categories: Routing (@app.get/post with path/query validation via Path() and Query(), APIRouter for modular routes, response_model for output serialization, HTTP status codes), Dependencies (Depends() for DB sessions and auth, sub-dependencies, class-based Pagination dependency), Models (Pydantic BaseModel, Field() validation, field_validator, Body() parameter, UploadFile), Middleware (@app.middleware, CORSMiddleware, TrustedHostMiddleware, HTTPException), Security (OAuth2PasswordBearer, HTTPBasic, JWT encode/decode, SecurityScopes), and Background (BackgroundTasks, startup/shutdown lifecycle events, WebSocket endpoint, StreamingResponse for SSE).
Key Features
- Async @app.get/@app.post routing with Path() and Query() parameter validation and constraints
- APIRouter with prefix and tags for modular, auto-documented route organization
- Depends() for database session management with yield-based context manager pattern
- Pydantic BaseModel with Field() validators and custom field_validator methods
- OAuth2PasswordBearer token extraction and JWT encode/decode with python-jose
- CORSMiddleware and TrustedHostMiddleware configuration for production security
- BackgroundTasks for fire-and-forget email/notification sending after HTTP response
- WebSocket endpoint and StreamingResponse for Server-Sent Events (SSE)
Frequently Asked Questions
What makes FastAPI different from Flask and Django REST Framework?
FastAPI is built on Starlette (ASGI) and Pydantic, offering native async/await support for high concurrency, automatic OpenAPI (Swagger) and ReDoc documentation generated from type annotations, and request/response validation via Pydantic at zero extra cost. Flask is synchronous by default and has no built-in validation or docs. Django REST Framework has more features out of the box but is heavier and not natively async.
How does dependency injection work in FastAPI with Depends()?
Depends() tells FastAPI to call the provided function and inject its return value as the parameter. For database sessions, use a generator function with yield: the code before yield runs before the route handler, the yield value is injected, and the code after yield runs as cleanup (e.g., closing the session). Dependencies can depend on other dependencies, creating a tree that FastAPI resolves automatically. Class instances work too — define __init__ parameters and FastAPI will inject them from query params.
How does Pydantic BaseModel handle request validation in FastAPI?
When a FastAPI route declares a parameter with a Pydantic BaseModel type, FastAPI automatically reads the request body, parses it as JSON, validates each field against the model's type annotations and Field() constraints, and returns a 422 Unprocessable Entity error with detailed messages if validation fails. Use Field(min_length=1, max_length=100) for string constraints, Field(gt=0) for numeric ranges, and @field_validator for custom validation logic.
How do I implement JWT authentication in FastAPI?
Install python-jose and passlib. Define an OAuth2PasswordBearer with the token URL. Create a get_current_user dependency that accepts a token string from Depends(oauth2_scheme), decodes it with jwt.decode(), and returns the user or raises HTTPException(401). Protect routes by adding Depends(get_current_user) as a parameter. Return tokens from a POST /token endpoint that verifies credentials and calls jwt.encode() with an expiry.
What is the difference between response_model and the actual return value in FastAPI?
The response_model parameter in a route decorator specifies the Pydantic model used to serialize and filter the response, regardless of what the route function actually returns. FastAPI will serialize the return value using only the fields defined in response_model, automatically excluding internal fields like passwords or database IDs you do not want to expose. Use response_model=list[Item] to return a list, and response_model_exclude_unset=True to omit unset optional fields.
How do BackgroundTasks work in FastAPI?
Declare a BackgroundTasks parameter in your route handler. FastAPI injects it automatically. Call bg.add_task(func, arg1, arg2) to schedule a function to run after the HTTP response is sent. The background task runs in the same process/thread pool as the server, so it is suitable for lightweight tasks like sending emails or logging. For heavy CPU-bound tasks, use Celery or a separate worker process instead.
How do I create a WebSocket endpoint in FastAPI?
Use the @app.websocket("/ws") decorator with a WebSocket parameter. Call await ws.accept() to complete the handshake, then use await ws.receive_text() or receive_bytes() to read messages and await ws.send_text() or send_json() to respond. Handle WebSocketDisconnect exceptions to clean up when the client disconnects. For broadcasting to multiple clients, maintain a list of active WebSocket connections.
How do I configure CORS in FastAPI for frontend access?
Import CORSMiddleware from fastapi.middleware.cors and call app.add_middleware(CORSMiddleware, allow_origins=["https://yourfrontend.com"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"]). Use allow_origins=["*"] only in development. For production, specify exact origins. The middleware adds Access-Control-Allow-Origin headers to responses and handles CORS preflight OPTIONS requests automatically.