Skip to main content

FastAPI Cheatsheet

At a glance​

What it isASGI web framework for APIs, built on Starlette + Pydantic, driven by type hints
Use it forJSON/REST APIs, ML model serving, async microservices with auto-generated OpenAPI docs
Latest stable0.162.0 (released 2026-10-23) - checked 2026-10-31
Official docsfastapi.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_model or return annotation).
  • Dependencies (Depends): reusable functions for DB sessions, auth, pagination; can yield for cleanup.
  • Annotated[...]: the recommended way to attach Query, Path, Depends metadata.
  • APIRouter: split routes per feature and include_router them.
  • async or sync: async def runs on the event loop; plain def runs 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
NeedUse
CORSapp.add_middleware(CORSMiddleware, allow_origins=[...])
Background work after responseBackgroundTasks.add_task(fn, ...)
Settings from envpydantic-settings BaseSettings
FilesUploadFile, File(); needs python-multipart
Real job queueCelery, RQ, arq, Dramatiq

Gotchas​

  • Blocking code in async def (requests, sync DB drivers, time.sleep) stalls every request; use plain def or async libraries.
  • Optional is not default: str | None without = None is still required.
  • Pydantic v2 API: model_dump() / model_validate(), not dict() / parse_obj(); model_config = ConfigDict(from_attributes=True) replaces orm_mode.
  • Route order matters: declare /users/me before /users/{id}.
  • response_model filters output: use it (or a return type) so you never leak fields like password_hash.
  • BackgroundTasks run 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 | None form fields now use their declared default (or raise a missing-field error) instead of being read as False.
  • 0.160.0 - 0.161.x (2026-10-22): query, header, cookie and form parameter models apply their extra setting 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 run CLI via fastapi[standard], Pydantic v2 as the default model layer, Python 3.10+ required (per PyPI metadata).

In these notes​