FastAPI Cheatsheet
At a glance
| What it is | ASGI web framework for APIs, built on Starlette + Pydantic, driven by type hints |
| Use it for | JSON/REST APIs, ML model serving, async microservices with auto-generated OpenAPI docs |
| Latest stable | 0.162.0 (released 2026-10-23) - checked 2026-10-31 |
| Official docs | fastapi.tiangolo.com |
Core concepts
- Type hints = contract: parameter types drive parsing, validation and the OpenAPI schema.
- Path operation: a decorated function (
@app.get("/items/{id}")). - Pydantic v2 models define request bodies and response shapes (
response_modelor return annotation). - Dependencies (
Depends): reusable functions for DB sessions, auth, pagination; canyieldfor cleanup. Annotated[...]: the recommended way to attachQuery,Path,Dependsmetadata.APIRouter: split routes per feature andinclude_routerthem.- async or sync:
async defruns on the event loop; plaindefruns in a threadpool. - Auto docs: Swagger UI at
/docs, ReDoc at/redoc, schema at/openapi.json.
Syntax & commands
pip install "fastapi[standard]" # includes uvicorn + fastapi CLI
fastapi dev main.py # auto-reload dev server
fastapi run main.py # production mode
uvicorn main:app --workers 4 # direct uvicorn
from typing import Annotated
from fastapi import FastAPI, Query, Path, HTTPException, status
from pydantic import BaseModel, Field
app = FastAPI(title="Shop API")
class ItemIn(BaseModel):
name: str = Field(min_length=1)
price: float = Field(gt=0)
tags: list[str] = []
class ItemOut(ItemIn):
id: int
@app.get("/items/{item_id}")
async def read_item(
item_id: Annotated[int, Path(ge=1)],
q: Annotated[str | None, Query(max_length=50)] = None,
):
return {"item_id": item_id, "q": q}
@app.post("/items", status_code=status.HTTP_201_CREATED)
async def create_item(item: ItemIn) -> ItemOut:
return ItemOut(id=1, **item.model_dump())
Common patterns
# DB session dependency with cleanup
from sqlalchemy.orm import Session
from fastapi import Depends
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
DB = Annotated[Session, Depends(get_db)]
@app.get("/users/{user_id}")
def get_user(user_id: int, db: DB):
user = db.get(User, user_id)
if user is None:
raise HTTPException(status_code=404, detail="User not found")
return user
# Routers + startup/shutdown with lifespan
from contextlib import asynccontextmanager
from fastapi import APIRouter
router = APIRouter(prefix="/orders", tags=["orders"])
@router.get("/")
async def list_orders(): ...
@asynccontextmanager
async def lifespan(app: FastAPI):
await connect_pool()
yield
await close_pool()
app = FastAPI(lifespan=lifespan)
app.include_router(router)
# Bearer token auth dependency
from fastapi.security import OAuth2PasswordBearer
oauth2 = OAuth2PasswordBearer(tokenUrl="token")
async def current_user(token: Annotated[str, Depends(oauth2)]) -> User:
return decode_token(token) # raise HTTPException(401) if invalid
# Test with TestClient (httpx under the hood)
from fastapi.testclient import TestClient
client = TestClient(app)
def test_read_item():
r = client.get("/items/1")
assert r.status_code == 200
app.dependency_overrides[get_db] = fake_db # swap dependencies in tests
| Need | Use |
|---|---|
| CORS | app.add_middleware(CORSMiddleware, allow_origins=[...]) |
| Background work after response | BackgroundTasks.add_task(fn, ...) |
| Settings from env | pydantic-settings BaseSettings |
| Files | UploadFile, File(); needs python-multipart |
| Real job queue | Celery, RQ, arq, Dramatiq |
Gotchas
- Blocking code in
async def(requests, sync DB drivers,time.sleep) stalls every request; use plaindefor async libraries. - Optional is not default:
str | Nonewithout= Noneis still required. - Pydantic v2 API:
model_dump()/model_validate(), notdict()/parse_obj();model_config = ConfigDict(from_attributes=True)replacesorm_mode. - Route order matters: declare
/users/mebefore/users/{id}. response_modelfilters output: use it (or a return type) so you never leak fields likepassword_hash.BackgroundTasksrun in the same process; long or critical jobs need a real queue.- Pre-1.0 versioning: minor bumps (0.x) can contain breaking changes; pin versions and read release notes.
What's new in recent releases
- 0.162.0 (2026-10-23): breaking: omitted
bool/bool | Noneform fields now use their declared default (or raise a missing-field error) instead of being read asFalse. - 0.160.0 - 0.161.x (2026-10-22): query, header, cookie and form parameter models apply their
extrasetting to sibling fields (breaking); unions of form models supported. - 0.158 - 0.159 (2026-10-21): optional form models and optional query/header/cookie parameter models.
- Longer-standing:
fastapi dev/fastapi runCLI viafastapi[standard], Pydantic v2 as the default model layer, Python 3.10+ required (per PyPI metadata).