FastAPI
Installation
SKILL.md
FastAPI Patterns
Async Traps
- Mixing sync database drivers (psycopg2, PyMySQL) in async endpoints blocks the event loop — use async drivers (asyncpg, aiomysql) or run sync code in
run_in_executor time.sleep()in async endpoints blocks everything — useawait asyncio.sleep()instead- CPU-bound work in async endpoints starves other requests — offload to
ProcessPoolExecutoror background workers - Async endpoints calling sync functions that do I/O still block — the entire call chain must be async
Pydantic Validation
- Default values in models become shared mutable state:
items: list = []shares the same list across requests — useField(default_factory=list) Optional[str]doesn't make a field optional in the request — add= Noneor useField(default=None)- Pydantic v2 uses
model_validate()notparse_obj(), andmodel_dump()not.dict()— v1 methods are deprecated - Use
Annotated[str, Field(min_length=1)]for reusable validated types instead of repeating constraints
Dependency Injection
- Dependencies run on every request by default — use
lru_cacheon expensive dependencies or cache in app.state for singletons Depends()without an argument reuses the type hint as the dependency — clean but can confuse readers- Nested dependencies form a DAG — if A depends on B and C, and both B and C depend on D, D runs once (cached per-request)
yielddependencies for cleanup (DB sessions, file handles) — code after yield runs even if the endpoint raises