Pirate Cheat Sheets
Typed Python web APIs with automatic docs

FastAPI
cheat sheet

FastAPI at a glance: the fastapi CLI, path operations, parameters, Pydantic models, dependencies, errors, routers, streaming and SSE, security, middleware, lifespan and testing.

Version
v0.165.0
Snippets
94
Sections
12

Version notes · FastAPI 0.165.0

  • 0.164 / 0.165 add request limits: FastAPI(max_body_size=…, form_limits={…}), also per router and route.
  • 0.163 adds Depends(dep, max_concurrency=5). 0.162.6 drops Python 3.10 (3.11+ now).
  • 0.146 deprecates FastAPI(root_path=…): use fastapi run --root-path /api. 0.143: OpenTelemetry auto-setup is opt-in.
  • 0.147–0.162 tightened form & body handling: omitted fields use defaults, JSON null ≠ missing, empty file inputs count as missing.

Declare endpoints as typed Python functions: FastAPI validates the input with Pydantic, serializes the output, and generates OpenAPI docs from the same type hints.

Built onStarlettePydanticUvicornOpenAPI

Validated input

from type hints, via Pydantic

Docs for free

/docs (Swagger) and /redoc

Async native

async def or def, both work

Dependencies

injection with Depends()

Quick start

uv init api && cd apiuv add "fastapi[standard]"printf 'from fastapi import FastAPI\napp = FastAPI()\[email protected]("/")\ndef root(): return {"hi": "there"}\n' > main.pyuv run fastapi dev   # → http://127.0.0.1:8000/docs
  1. 1fastapi devRun with reload
  2. 2@app.getAdd endpoints
  3. 3BaseModelType the data
  4. 4DependsShare logic
  5. 5TestClientTest it
  6. 6fastapi runServe in prod
  • FastAPI + CLI + Uvicorn + extras
  • Bare framework, bring your own server
  • Dev server with reload (finds main.py, app/main.py…)
  • A specific file
  • An import string
  • Production: no reload, listens on 0.0.0.0:8000
  • Several worker processes
  • Behind a proxy that strips /api
  • Trust X-Forwarded-* (on by default)
  • Show how the app was found
  • Deploy to FastAPI Cloud (after fastapi login)

pyproject.toml

[tool.fastapi]entrypoint = "api.main:app"# then just:#   fastapi dev#   fastapi run

Docs at /docs (Swagger UI), /redoc, and the schema at /openapi.json. Turn them off with FastAPI(docs_url=None, redoc_url=None).

  • The app (title shows in /docs)
  • GET route (also post, put, patch, delete…)
  • Path parameter
  • Typed: /items/abc → 422
  • Query params: ?skip=20&limit=5
  • Optional query param
  • Status code for success
  • Docs grouping and text
  • Several methods
  • Path param that may contain /
  • Mark as deprecated in docs

Use async def when you await things; plain def runs in a thread pool. Blocking calls inside async def stall every request.

  • Metadata goes in Annotated
  • Bounds on a query param
  • String constraints
  • Repeated ?tags=a&tags=b
  • Constraints on a path param
  • Header (user-agent)
  • Cookie
  • All query params as one model
  • Body as {"item": {…}}
  • Form field (needs python-multipart)
  • Uploaded file: await file.read(), .filename
  • The raw Starlette request
  • Request / response schema (Pydantic)
  • Field rules + docs
  • A model parameter = JSON body
  • Return type = response model + filtering
  • Declare it on the decorator instead
  • Omit fields that weren’t set
  • Lists work too
  • Separate in / out models: never return secrets
  • Reject unknown fields

main.py

from fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModelapp = FastAPI()class Item(BaseModel):    name: str    price: floatDB: dict[int, Item] = {}@app.post("/items/{id}",          status_code=201)def create(id: int, item: Item):    DB[id] = item    return item@app.get("/items/{id}")def read(id: int) -> Item:    if id not in DB:        raise HTTPException(404)    return DB[id]

With a Pydantic return type, FastAPI serializes the response in Rust (0.130+): about twice as fast as returning a plain dict.

  • Inject a value per request
  • Reusable alias: def read(db: DB)
  • yield: setup + teardown
  • Teardown after the response is sent
  • At most 5 at once, others wait (0.163+)
  • Run it, ignore the value
  • Every route in a router
  • Every route in the app
  • Call again even within one request

Dependencies can depend on other dependencies, and on request params. Within one request each is called once and the result is shared.

  • {"detail": "Item not found"}
  • With headers
  • Map your exception to a response
  • The handler
  • 422 errors: override their handler
  • Re-use the default handler
  • A group of routes (in routers/users.py)
  • → /users/{user_id}
  • Mount it
  • Prefix + guard at include time
  • Nest routers (order no longer matters, 0.137+)
  • Serve static files
  • Serve a SPA build with fallback (0.138+)
  • Explicit response
  • HTML (PlainTextResponse too)
  • Redirect
  • Send a file
  • yield items → JSON Lines stream (0.134+)
  • Server-Sent Events: yield items (0.135+)
  • SSE fields (fastapi.sse)
  • Stream raw bytes / text
  • Set headers / cookies
  • Run after the response (BackgroundTasks)
  • Bearer token from Authorization
  • Missing token → 401
  • Plain Authorization: Bearer …
  • API key header (APIKeyQuery, APIKeyCookie)
  • Login form for /token
  • OAuth2 scopes

Security dependencies show a lock + "Authorize" button in /docs. Since 0.144 they work on WebSocket routes too.

  • CORS
  • Compress responses
  • Custom: async def mw(request, call_next)
  • Startup / shutdown (@asynccontextmanager)
  • Lifespan body
  • Reject bigger bodies with 413 (0.164+)
  • Form parsing limits (0.165+)
  • Per-route limit
  • Accept JSON without Content-Type (0.132+)
  • Sync test client (httpx based)
  • No server needed
  • Call like httpx
  • Also runs the lifespan
  • Swap a dependency in tests
  • Async tests (with anyio / pytest-asyncio)