What is FastAPI dependency injection and how does Depends resolve it per request?
In FastAPI, Depends marks the boundary where a route stops building its own resources and asks the framework for them. The route declares what it needs, such as a database session or an authenticated user. The dependency owns how that thing is created, validated, and cleaned up. This matters most for backend and platform engineers running services with a database and authenticated routes. The alternative is session handling and token checks copied into every handler, where they drift apart over time.
How resolution works per request
When a request arrives, FastAPI reads the signature of the path operation and finds every Depends. It then recurses into each dependency's own parameters, which produces a dependency graph. The leaves resolve first, and their results are passed upward. FastAPI rebuilds this graph for every request, so no state from one request reaches the next unless you put it in a module-level object yourself.
Within a single request, each dependency's result is cached by default. If get_current_user and the route both depend on get_db, get_db runs once and both receive the same session. That shared session is what keeps them inside one transaction.
route handler ──────────────────────────┐
│ │
▼ │
require_role("admin") │
│ │
▼ │
get_current_user │
│ │ │
▼ ▼ ▼
credential get_db ◄──────── (cache hit)
extractor resolved once → session S
Pass use_cache=False when you need a fresh value at each use site. One case is a separate session for an audit write that must commit even if the main transaction rolls back. Another is a dependency whose result is meant to change between calls.
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session, sessionmaker
engine = create_engine("postgresql+psycopg://app:changeme@db.internal:5432/app")
SessionLocal = sessionmaker(bind=engine)
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") # credential extractor
app = FastAPI()
def get_db():
# Owns the session lifecycle: open per request, always close afterwards.
db = SessionLocal()
try:
yield db
finally:
db.close()
def get_current_user(token: Annotated[str, Depends(oauth2_scheme)],
db: Annotated[Session, Depends(get_db)]):
# Simplified lookup; real code would verify a signed token or a hashed value.
user = db.execute(text("SELECT id, role FROM users WHERE api_token = :t"), {"t": token}).first()
if user is None:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
return user
def require_role(role: str):
def checker(user=Depends(get_current_user)):
if user.role != role:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
return user
return checker
@app.delete("/projects/{project_id}")
def delete_project(project_id: int,
user=Depends(require_role("admin")),
db: Session = Depends(get_db), # cache hit: same session get_current_user used
audit_db: Session = Depends(get_db, use_cache=False)): # fresh, separate session
db.execute(text("DELETE FROM projects WHERE id = :id"), {"id": project_id})
db.commit()
# Audit write commits independently of the main transaction.
audit_db.execute(text("INSERT INTO audit_log (user_id, action) VALUES (:u, 'delete_project')"), {"u": user.id})
audit_db.commit()
return {"deleted": project_id}
A route depends on require_role, which chains through get_current_user to the credential extractor and get_db. The route's own get_db reuses the cached session from that chain, while use_cache=False gives the audit write a separate session.
How do you write a yield-based get_db dependency that manages DB sessions?
The standard pattern is a generator dependency. get_db asks a session factory for a new session, yields it to the handler, and closes it in a finally block. Because the close sits in finally, the connection goes back to the pool even when the handler raises. Code before yield is setup and code after it is teardown, so each request gets exactly one session for its whole lifetime.
The harder question is where commit and rollback should live.
| Location | Strength | Risk |
|---|---|---|
| Handler | Transaction boundary is visible at the endpoint | Commit calls get repeated across handlers |
| Service layer | Business operation defines the unit of work | Services must receive the session explicitly |
| Dependency | One place, no repetition | Hides boundaries; can commit unwanted state |
Any of these can work. Mixing them is what causes trouble: a service commits, then the dependency commits again, and nobody knows which call is the real boundary. Choose one rule and enforce it in review.
Auto-commit in the dependency has a specific failure mode. Suppose a handler catches an exception and returns a 409 or 422 response itself. The dependency then sees a normal exit and commits whatever partial writes the handler made before the error.
Timing matters too. When the code after yield runs relative to sending the response has differed between FastAPI versions. In some versions it runs after the response has already started or finished. An exception raised there cannot change a status code the client has already received. For that reason, any commit whose failure the client must see belongs in the handler or the service layer, before the response is returned.
from typing import Annotated, Iterator
from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy import create_engine
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, sessionmaker
from app.models import User # placeholder ORM model with a unique email column
engine = create_engine("postgresql+psycopg://app:example-password@db.internal:5432/app")
SessionLocal = sessionmaker(bind=engine)
app = FastAPI()
def get_db() -> Iterator[Session]:
db = SessionLocal() # setup: one session per request
try:
yield db
finally:
# Teardown only. No commit here: post-yield code may run after the
# response is sent, so it cannot report failures to the client.
# close() returns the connection to the pool and discards uncommitted work.
db.close()
DB = Annotated[Session, Depends(get_db)]
@app.post("/users", status_code=201)
def create_user(email: str, db: DB):
db.add(User(email=email))
try:
# Team rule: the handler owns the transaction boundary. Committing
# before return means a failed commit becomes a response the client sees.
db.commit()
except IntegrityError:
# Roll back explicitly so the error response never sits on top of
# partial writes that a later commit could persist.
db.rollback()
raise HTTPException(status_code=409, detail="email already registered")
return {"email": email}
A yield-based get_db that only creates and closes the session, with the handler committing before it returns and rolling back explicitly on a conflict, so the client sees the real outcome of the transaction.
Should DB dependencies be sync or async?
The session type also decides where your code runs. FastAPI checks each dependency and handler. A plain def function is sent to a worker threadpool, so a blocking driver call ties up a thread and leaves the event loop free. An async def function runs directly on the event loop, and FastAPI assumes it will yield control at every await.
That assumption is why blocking calls inside async def are harmful. A synchronous query in an async def handler holds the event loop thread until the database responds. During that time no other request on that worker can progress, including health checks and requests that never touch the database. Under load, latency rises across the whole process, not only on the slow endpoint.
| Combination | Where queries run | Outcome |
|---|---|---|
def dependency + sync session, used in def handlers |
Threadpool | Safe. Concurrency is limited by threadpool and connection pool size. |
async def dependency + async session, awaited in async def handlers |
Event loop, non-blocking | Safe. Every query and commit must be awaited. |
Sync session queried inside an async def handler or dependency |
Event loop, blocking | Avoid. A single slow query stalls every request on the worker. |
The mixed case is easy to miss. A def dependency that yields a sync session runs its setup in the threadpool. If the handler is async def, though, the queries it makes on that session still block the event loop.
The rule: queries should run in the same kind of function as the session. Use sync sessions with def handlers and async sessions with async def handlers, and do not mix them on one route.
from typing import Annotated
from fastapi import Depends, FastAPI
from sqlalchemy import create_engine, text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import Session, sessionmaker
app = FastAPI()
# Placeholder DSNs: psycopg (sync driver) and asyncpg (async driver).
sync_engine = create_engine("postgresql+psycopg://app:changeme@db:5432/app")
async_engine = create_async_engine("postgresql+asyncpg://app:changeme@db:5432/app")
SyncSessionLocal = sessionmaker(sync_engine)
AsyncSessionLocal = async_sessionmaker(async_engine)
def get_sync_session(): # def: FastAPI runs setup and teardown in the threadpool
with SyncSessionLocal() as session:
yield session
async def get_async_session(): # async def: runs on the event loop
async with AsyncSessionLocal() as session:
yield session
# Safe: def handler + sync session. The blocking query occupies a worker thread.
@app.get("/sync/users/count")
def count_users_sync(session: Annotated[Session, Depends(get_sync_session)]):
return {"count": session.execute(text("SELECT count(*) FROM users")).scalar_one()}
# Safe: async def handler + async session. The await yields the loop during I/O.
@app.get("/async/users/count")
async def count_users_async(session: Annotated[AsyncSession, Depends(get_async_session)]):
result = await session.execute(text("SELECT count(*) FROM users"))
return {"count": result.scalar_one()}
# Avoid: the dependency's setup ran in the threadpool, but this query runs
# on the event loop and blocks every other request on the worker until it returns.
@app.get("/mixed/users/count")
async def count_users_mixed(session: Annotated[Session, Depends(get_sync_session)]):
return {"count": session.execute(text("SELECT count(*) FROM users")).scalar_one()}
Two safe pairings, a def handler with a sync SQLAlchemy session and an async def handler with an awaited AsyncSession, next to the mixed case where a sync query inside an async def handler blocks the event loop.
How do you build layered auth dependencies with get_current_user?
Start with credential extraction, kept separate from validation. OAuth2PasswordBearer(tokenUrl="token") reads the Authorization: Bearer header and returns the raw token string. It also adds the security scheme to the OpenAPI docs. If your clients send something else, such as an API key, a plain function that takes a Header parameter does the same job. Keeping extraction separate means you can change the transport without touching validation logic.
get_current_user then depends on both the token and get_db. It decodes and verifies the token, loads the user, and raises a 401 with a WWW-Authenticate header on failure. FastAPI caches dependency results within a request, so this function receives the same session the handler gets. Narrower checks stack on top. require_active_user depends on get_current_user and rejects disabled accounts. It does not repeat the decode step.
For parameterized rules, use a callable class whose __init__ takes the required role or scope and whose __call__ declares the user dependency. A factory function that returns an inner dependency works the same way. A route then declares Depends(RoleChecker("admin")), so the permission rule is visible in the route signature instead of buried in the handler body. Alias common forms with Annotated, for example CurrentUser = Annotated[User, Depends(require_active_user)], to keep signatures short.
Router- or app-level dependencies=[...] enforce auth on every route. Their return values are discarded, so a handler that needs the user must still declare it. Request caching means the check doesn't run twice.
Each request costs a token verification plus a user query. Embedding roles in the token removes the query. The trade-off is that deactivations and role changes go unnoticed until the token expires. Either keep token lifetimes short or check a revocation list.
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session
from app.db import get_db # shared per-request session dependency
from app.models import User
from app.tokens import decode_token # verifies signature/expiry; raises ValueError on failure
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") # extraction only: returns raw bearer string
def get_current_user(token: Annotated[str, Depends(oauth2_scheme)],
db: Annotated[Session, Depends(get_db)]) -> User:
unauthorized = HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid credentials",
headers={"WWW-Authenticate": "Bearer"})
try:
user_id = int(decode_token(token)["sub"])
except (ValueError, KeyError):
raise unauthorized from None
user = db.get(User, user_id) # same session the handler receives (per-request cache)
if user is None:
raise unauthorized
return user
def require_active_user(user: Annotated[User, Depends(get_current_user)]) -> User:
if not user.is_active: # narrower rule; no second decode
raise HTTPException(status.HTTP_403_FORBIDDEN, "Inactive user")
return user
CurrentUser = Annotated[User, Depends(require_active_user)]
class RoleChecker: # parameterized dependency: rule lives in the route signature
def __init__(self, role: str):
self.role = role
def __call__(self, user: CurrentUser) -> User:
if self.role not in user.roles:
raise HTTPException(status.HTTP_403_FORBIDDEN, "Insufficient role")
return user
# Enforced on every route in the router, but the return value is discarded.
router = APIRouter(prefix="/admin", dependencies=[Depends(RoleChecker("admin"))])
@router.get("/me")
def admin_me(user: CurrentUser): # must still declare the user; cached, so no extra query
return {"id": user.id}
Layered auth dependencies: bearer extraction, get_current_user reusing get_db, require_active_user, a RoleChecker callable class, an Annotated alias, and a router-level check whose result handlers must re-declare.
How do you test FastAPI dependencies with dependency_overrides?
app.dependency_overrides is a plain dictionary on the application object. Its keys are the original dependency callables and its values are replacements. When FastAPI resolves Depends(get_db) during a request, it checks this dictionary first. The key must be the exact function object your routes reference, so import get_db from the same module the routes use.
For the database, the override opens a connection, begins a transaction, binds a session to that connection, yields the session, and rolls back in its teardown. Each test sees its own writes, and nothing persists afterward. You avoid truncating tables or rebuilding the schema between tests. If the code under test calls commit(), use a savepoint-based setup so the commit releases a savepoint rather than ending the outer transaction. Otherwise the final rollback has nothing to undo.
For auth, override get_current_user with a function that returns a fixed user object. Role checks layered on top of it still run, so you can test authorization by changing that user's roles. You don't need to mint tokens.
Put both overrides in a pytest fixture: assign them, yield the test client, then clear them after the yield. The dictionary is global mutable state. If a test sets an override and never removes it, every later test in the same process inherits the change. Popping only the keys you set is safer than clear() when several fixtures each install their own overrides. The same leakage applies to tests that run concurrently against one shared app instance.
This approach saves engineering time. You swap one function at the boundary FastAPI already defines, instead of patching internals that break when someone refactors, or running a full login flow in every test.
When should you avoid relying on request-scoped dependencies?
Request-scoped dependencies fit short, synchronous request/response cycles. Outside that pattern they cause problems that are hard to see in development and appear under load.
A get_db session that lives for the whole request holds a pool connection for the handler's full duration. That includes time spent awaiting a slow upstream API or streaming a large export. With a small pool and many concurrent requests, each one idles on a connection it isn't using, and new requests queue until the pool times out. Background tasks and streaming generators make this worse. Depending on your FastAPI version, they can run during or after dependency teardown, so the session they captured may already be closed or committed. Don't rely on either ordering.
| Situation | Risk | Mitigation |
|---|---|---|
| Slow handler or streaming response | Pool slot held while idle | Open a short-lived session only around the queries, and release it before slow I/O |
| Background task | Session closed under it | Pass IDs, not ORM objects; have the task open its own session |
| Deep dependency chains | Hard to trace, per-request overhead | Collapse into a few well-named dependencies |
| Per-request caching | Two Depends(get_db) calls return the same session |
Use use_cache=False when isolation is needed, and document it |
| Router-level auth | New routers or excluded paths go unprotected | Add a test that walks app.routes and asserts the auth dependency is present |
Caching surprises people because FastAPI deduplicates a dependency within one request by default. A rollback in one sub-dependency then silently affects another that shares the same session.
What are the alternatives to FastAPI Depends, and how do they affect development cost?
The rule that keeps any of these options cheap is to put no business logic in dependencies. A dependency supplies a resource, such as a session, or an identity, such as the current user. A service function takes those as plain arguments. A background job or CLI can then call the same service with a session it opened itself, without importing FastAPI or building a fake request.
| Approach | Lifecycle control | Testability | Coupling to FastAPI | Maintenance cost |
|---|---|---|---|---|
Depends with yield |
Per request, with explicit teardown | High: dependency_overrides swaps resources |
High at the edge, none in services | Low once the conventions are set |
| Middleware for auth | Per request, but not per route | Medium: tests go through the full stack | Medium | Low for blanket rules, high for per-route exceptions |
| Session per service call or context manager | Per call, with clear boundaries | High: pass a session in | None | Low, but multi-step transactions need care |
| Global or module-level session | None, shared across requests | Low: hidden state leaks between tests | Low | High: concurrency and stale-state bugs |
| Standalone DI container | Configurable scopes | High | None | Medium: one more framework to learn |
Depends pays off when handlers stay thin, every route follows the same commit and rollback rule, and tests need cheap swaps of the database or auth. Middleware still suits blanket checks such as rejecting unauthenticated traffic on a whole prefix. For small scripts, queue consumers, or other non-HTTP workers, the request-scoped structure only adds overhead. A plain context manager around the service call gives the same lifecycle guarantees with less machinery.
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to fastapi dependency injection, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Changing a route's URL or method automatically notifies the services that consume it — no hunting through repos for callers.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Consumers learn about a breaking change at review time rather than from production errors.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.