FastAPI MOC
Hub for how FastAPI works: where its speed comes from, how it reads request data, and how to structure an app around it.
Core concepts
Runtime & performance
- FastAPI Is Fast Only While async Endpoints Never Block the Event Loop: Starlette (ASGI) handles HTTP and Pydantic handles data;
defendpoints run in a threadpool,async defon the event loop, where one blocking call stalls every request.
Request data
- Routes Match in Declaration Order, So a Dynamic Path Can Shadow a Static One: static before dynamic paths,
422on shadowed routes, the same rule in Rails and Django. - FastAPI Reads Each Parameter from the Path, Query, Body or Headers According to Its Declaration: path template names, singular types as query, Pydantic models as body, explicit
Body()/Header(); trailing-slash307redirects and why GET carries no body.
Application structure
- Only the Route Layer of a FastAPI App Should Raise HTTP Errors: routes, services and data access split by concern; domain exceptions in services,
HTTPExceptiononly in routes, and neverstr(e)in a response. - Separate SQLModel Classes for Table, Create, Update and Read Keep Validation Honest: base, table, create, update and list models; import-time field arguments, ISBN length, Pydantic v2 config.
- Relative Template Directories Resolve Against the Working Directory, Not the Source File:
Jinja2Templates(directory="templates")breaks under test runners; build the path fromPath(__file__). - Circular Imports Fail at Import Time, So Shared Objects Belong in a Module Neither Side Imports: shared templates in a config module,
TYPE_CHECKINGfor model relationships. - A Python Decorator Replaces a Function with Whatever It Returns: wrappers, decorator arguments, and route registration with
@app.getandAPIRouter. - Build Derived Data at Deploy Time When Production Should Not See the Source Files: a knowledge graph built to JSON at deploy time and served statically.
Testing
- Point the App at a Test Database Before It Imports Its Connection: overriding
SQLITE_DATABASEinconftest.pybefore the import,:memory:and an autouse reset fixture.
Runbooks (05 - SOPs & Manuals/)
- Start a FastAPI Project with uv:
uv init,fastapi[standard], a first endpoint andfastapi dev.
Related maps
- Programming Languages MOC: Python and REST API notes.
- Software Testing MOC: test levels, isolation and test databases.
- Docker and Container Security MOC: containerising FastAPI apps (uv, proxies, static files).
References
- FastAPI documentation - the official tutorial and reference for every note above.