7. Dependencies, Exceptions & Routing
So far, the app is a single-file main.py handling routing, database access, and boilerplate that does a db lookup or 404s.
This chapter introduces:
- Inject dependencies with
Annotated: A deeper look at how FastAPI'sDependssystem actually works underSessionDep. - DRY routes with
ProjectDep: A custom dependency that handles the lookup-and-404 pattern for any route that takes aproject_id. - Centralized exception handling: Catch
IntegrityErroronce inmain.pysocrud.pystops needing FastAPI imports and routes stop needingtry/except. - APIRouter: Move the project endpoints into their own module so
main.pybecomes a thin configuration layer.