Skip to content

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's Depends system actually works under SessionDep.
  • DRY routes with ProjectDep: A custom dependency that handles the lookup-and-404 pattern for any route that takes a project_id.
  • Centralized exception handling: Catch IntegrityError once in main.py so crud.py stops needing FastAPI imports and routes stop needing try/except.
  • APIRouter: Move the project endpoints into their own module so main.py becomes a thin configuration layer.