On this page
The core idea
In FastAPI, a dependency is a function that a route declares with Depends. FastAPI calls it before the route, passes its result in as a parameter and can run cleanup code afterwards when the dependency uses yield. Dependencies can depend on other dependencies, so a current-user dependency can rely on a token dependency, which relies on settings. This keeps routes focused on their own logic, makes requirements visible in the function signature and lets tests replace any dependency with a fake.
A practical approach
Step 1
Create a settings dependency that loads and validates configuration once, for example with a cached function returning a settings object.
Step 2
Create a database session dependency that opens a session, yields it to the route and closes it in a finally block so connections are always released.
Step 3
Create a get_current_user dependency that reads the token, verifies it and raises HTTPException with status 401 when it is missing or invalid.
Step 4
Build narrower dependencies on top, such as require_admin, which depends on get_current_user and raises 403 for users without the role.
Step 5
In tests, use app.dependency_overrides to replace the database or user dependency with fakes, so route tests do not need real tokens.
Worked example
An internal course-management API had twelve routes, each decoding a token and opening a database connection by hand. Two newer routes forgot the role check, and connections leaked when exceptions occurred. Introducing get_db, get_current_user and require_editor dependencies reduced each route to its business logic, fixed the missing checks by making them part of the signature and guaranteed sessions closed even on errors.
A mistake to avoid
Do not perform slow work, such as calling external services, in a dependency used by every route unless it is cached appropriately. Dependencies run on each request, and an expensive one silently slows the whole API.
Try it yourself
Add a get_current_user dependency to a small FastAPI project and protect two routes with it. Write one test that overrides the dependency with a fake user and one test that sends no token and expects a 401.
Your implementation checklist
- Shared concerns are implemented as dependencies, not copied into routes
- Database sessions are always closed through a yield dependency
- Authorisation rules are visible in route signatures
- Tests override dependencies instead of using real credentials
- Expensive dependencies are cached or scoped appropriately
Share or cite this guide
Innovate with Ajay Editorial (2026-10-07). Use FastAPI Dependencies for Authentication, Sessions and Settings. https://innovatewithajay.com/blogs/use-fastapi-dependencies
