FastAPI Cheat Sheet

Quick reference for FastAPI — app setup, path operations, request/response models, dependency injection, middleware, CORS, and authentication. All essential patterns in one page.

App Setup Path Operations Request Parameters Response Models Dependencies Middleware & CORS Authentication

App Setup

from fastapi import FastAPI Import FastAPI
app = FastAPI(title="My API", version="1.0.0") Create app instance with metadata
uvicorn main:app --reload Run dev server with hot reload
uvicorn main:app --host 0.0.0.0 --port 8000 Run production server
/docs Auto-generated Swagger UI (built-in)
/redoc Auto-generated ReDoc documentation
app = FastAPI(lifespan=lifespan) App lifespan events (startup/shutdown)
from fastapi import APIRouter; router = APIRouter(prefix="/api") Create modular router
app.include_router(router, tags=["users"]) Mount router with tags

Path Operations

@app.get("/") GET endpoint
@app.post("/items", status_code=201) POST endpoint with status code
@app.put("/items/{id}") PUT endpoint with path param
@app.patch("/items/{id}") PATCH endpoint for partial update
@app.delete("/items/{id}", status_code=204) DELETE endpoint
@app.get("/items", response_model=list[Item]) Endpoint with response model
@app.get("/items", deprecated=True) Mark endpoint as deprecated
@app.get("/items", summary="List items", description="...") Endpoint documentation

Request Parameters

def read(id: int): Path parameter with type validation
def read(id: int = Path(ge=1, le=1000)): Path param with constraints
def read(skip: int = 0, limit: int = 10): Query parameters with defaults
def read(q: str | None = Query(None, max_length=50)): Optional query param with validation
def read(item: Item): Request body (Pydantic model)
def read(x_token: str = Header()): Header parameter
def read(session: str = Cookie()): Cookie parameter
def read(file: UploadFile): File upload parameter
def read(files: list[UploadFile]): Multiple file upload
def read(data: Annotated[Item, Body(embed=True)]): Annotated body parameter

Response Models

class Item(BaseModel): name: str; price: float Pydantic v2 model
class Item(BaseModel): model_config = ConfigDict(from_attributes=True) ORM mode (Pydantic v2)
name: str = Field(min_length=1, max_length=100) Field with validation constraints
price: float = Field(gt=0, description="Item price") Field with numeric constraint
tags: list[str] = Field(default_factory=list) List field with default
@field_validator("name") @classmethod def validate(cls, v): Custom field validator (Pydantic v2)
@model_validator(mode="after") def check(self): Model-level validator (Pydantic v2)
return JSONResponse(content={...}, status_code=200) Custom JSON response
from fastapi.responses import StreamingResponse Streaming response for large data

Dependencies

def get_db(): db = SessionLocal(); yield db; db.close() Database session dependency with cleanup
@app.get("/", dependencies=[Depends(verify_token)]) Dependency without return value
def common(skip: int = 0, limit: int = 10): Reusable query param dependency
async def get_current_user(token: str = Depends(oauth2_scheme)): Auth dependency chain
app = FastAPI(dependencies=[Depends(verify_api_key)]) Global dependency for all routes
Annotated[Session, Depends(get_db)] Annotated dependency (recommended)

Middleware & CORS

app.add_middleware(CORSMiddleware, allow_origins=["*"]) Enable CORS for all origins
allow_methods=["GET","POST"], allow_headers=["Authorization"] CORS with specific methods/headers
@app.middleware("http") async def log(request, call_next): Custom middleware function
response = await call_next(request); return response Process request in middleware
app.add_middleware(TrustedHostMiddleware, allowed_hosts=["example.com"]) Trusted host validation
app.add_middleware(GZipMiddleware, minimum_size=1000) GZip compression middleware
from starlette.middleware.sessions import SessionMiddleware Session middleware

Authentication

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") OAuth2 password bearer scheme
@app.post("/token") async def login(form: OAuth2PasswordRequestForm = Depends()): Login endpoint
access_token = jwt.encode({"sub": user.email, "exp": expire}, SECRET) Create JWT token
payload = jwt.decode(token, SECRET, algorithms=["HS256"]) Decode and verify JWT
from passlib.context import CryptContext; pwd = CryptContext(schemes=["bcrypt"]) Password hashing setup
pwd.hash(password) / pwd.verify(plain, hashed) Hash and verify passwords
Security(api_key_header) API key authentication
HTTPBearer(auto_error=True) Bearer token auth scheme

Try It Live

Test these patterns with our free API Tester. No signup needed.

Open API Tester →
Step-by-Step Guide

How to Test an API Online

Read Guide →

More Cheat Sheets