What is FastAPI dependency injection and how does Depends resolve a request?

This guide is for backend and platform engineers running FastAPI against a relational database who want session handling and service wiring that stay correct as the codebase grows.

FastAPI dependency injection is a per-request wiring layer, not a full DI container. There is no global registry of bindings, no scopes beyond the request, and no automatic lifetime management for long-lived objects. You declare what a path operation needs with Depends(callable). On each request, FastAPI inspects that callable's parameters, resolves any of them that are themselves dependencies, and passes the results in. This continues recursively until it reaches values it can take directly from the request, such as path parameters, headers, or the body.

Within a single request, results are cached by default. If get_session appears in the endpoint, in a service dependency, and in two repository dependencies, FastAPI calls it once and hands the same object to all four. That default is what lets a service and its repositories share one database session, and therefore one transaction, without passing the session around by hand. To opt out for a specific dependency, use Depends(get_session, use_cache=False), which gives a fresh call each time it appears. That is rarely what you want for sessions.

Writing session: Session = Depends(get_session) in every signature becomes repetitive. The cleaner pattern is to define the alias once, SessionDep = Annotated[Session, Depends(get_session)], and annotate parameters as session: SessionDep. Because Annotated preserves Session as the real type, type checkers and editors still see the correct type for autocompletion and error checking. FastAPI reads the Depends metadata to perform the wiring.

from typing import Annotated, Iterator

from fastapi import Depends, FastAPI
from sqlalchemy import create_engine
from sqlalchemy.orm import Session

engine = create_engine("postgresql+psycopg://app:change-me@localhost:5432/appdb")
app = FastAPI()

def get_session() -> Iterator[Session]:
    # One session per request, closed when the request is finished.
    with Session(engine) as session:
        yield session

# Declare the alias once. Editors and type checkers still see `Session`.
SessionDep = Annotated[Session, Depends(get_session)]

class OrderRepo:
    def __init__(self, session: SessionDep):
        self.session = session

class AuditRepo:
    def __init__(self, session: SessionDep):
        self.session = session

class OrderService:
    # Depends() with no argument uses the annotated class as the dependency.
    def __init__(self, orders: Annotated[OrderRepo, Depends()], audit: Annotated[AuditRepo, Depends()]):
        self.orders, self.audit = orders, audit

ServiceDep = Annotated[OrderService, Depends()]

@app.get("/orders/{order_id}")
def read_order(order_id: int, service: ServiceDep, session: SessionDep,
               isolated: Annotated[Session, Depends(get_session, use_cache=False)]):
    # get_session ran once for the service, both repos and the endpoint: one session.
    assert service.orders.session is service.audit.session is session
    # use_cache=False forced a second, separate call and session.
    assert isolated is not session
    return {"order_id": order_id}

A service and two repositories are wired with Annotated aliases. Per-request caching gives all of them the same SQLAlchemy session, and a use_cache=False dependency gets its own separate session.

Why separate engine lifetime from session lifetime?

Opening a database connection costs a TCP handshake, authentication and often TLS negotiation. The engine exists to pay that cost rarely. It owns the connection pool, so it should be built once at startup and shared by every request. A session is a unit of work: it tracks loaded objects in its identity map, holds pending changes and wraps one transaction. That state belongs to a single request and should end with it.

Create the engine inside the application's lifespan handler, the async context manager you pass to FastAPI(lifespan=...). Before the yield, build the engine and a session factory and attach both to app.state. After the yield, call engine.dispose() so pooled connections close cleanly on shutdown and are not dropped by the process exiting. The session dependency then reads the factory from request.app.state, so nothing is created at import time. Tests can swap the factory without patching modules.

A module-level session shared across requests is unsafe. A SQLAlchemy Session is not thread-safe, and FastAPI runs plain def endpoints in a threadpool, so concurrent requests can use one session at the same time. Async endpoints run into the same problem when coroutines interleave. One request's rollback can discard another request's pending writes. The identity map also keeps serving cached objects from earlier requests, which hides fresh database state.

Object Created Lives for Stored on
Engine / pool Once, in lifespan startup Whole process, disposed at shutdown app.state
Session Once per request, in a yield dependency One request / one transaction Dependency scope
Service instance Once per request, by its dependency One request Dependency scope (holds the session)
from contextlib import asynccontextmanager
from typing import AsyncIterator

from fastapi import Depends, FastAPI, Request
from sqlalchemy import text
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine

DATABASE_URL = "postgresql+asyncpg://app:change-me@db.internal:5432/orders"

@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    # Engine and pool: built once per process and shared by every request.
    engine = create_async_engine(DATABASE_URL, pool_size=10, pool_pre_ping=True)
    app.state.engine = engine
    app.state.session_factory = async_sessionmaker(engine, expire_on_commit=False)
    yield
    # Close pooled connections cleanly instead of letting process exit drop them.
    await engine.dispose()

app = FastAPI(lifespan=lifespan)

async def get_session(request: Request) -> AsyncIterator[AsyncSession]:
    # One session per request. Reading the factory from app state lets tests swap it.
    async with request.app.state.session_factory() as session:
        yield session  # closed (and any open transaction rolled back) after the response

class OrderService:
    def __init__(self, session: AsyncSession) -> None:
        self.session = session  # per-request service holds the per-request session

    async def count(self) -> int:
        result = await self.session.execute(text("SELECT count(*) FROM orders"))
        return result.scalar_one()

def get_order_service(session: AsyncSession = Depends(get_session)) -> OrderService:
    return OrderService(session)

@app.get("/orders/count")
async def order_count(service: OrderService = Depends(get_order_service)) -> dict:
    return {"count": await service.count()}

The engine and session factory are created once in the lifespan handler, stored on app.state and disposed at shutdown, while each request gets its own session and a service instance that wraps it.

How do you write a yield dependency that owns the transaction?

The dependency opens a session, yields it, and then wraps the yield in try/except/finally. If the endpoint returns normally, it commits. If the endpoint raises, it rolls back. In every case it closes the session in finally.

This works because FastAPI raises an exception from the endpoint back into the dependency at the yield statement. That means the except block sees the real error. It must re-raise after rolling back. If it swallows the exception, the client gets a success response for work that was never committed, or the error turns into a generic failure that no longer points to its cause.

Committing manually in each endpoint spreads transaction boundaries across dozens of handlers. Sooner or later one of them forgets to commit or roll back. A single boundary per request gives you one rule: the request either succeeds and commits, or it fails and nothing persists.

The trade-off is timing. A commit after yield can fail after the response has already been decided. Teams that need commit errors, such as constraint violations, to shape the response can commit explicitly in the service layer and keep the dependency responsible only for rollback and close.

Sync and async need separate variants:

Aspect Sync variant Async variant
Declared as def async def
Runs in Threadpool Event loop
Session type Session AsyncSession
Driver Blocking DB-API driver Async-native driver

The session type and driver must match. A blocking driver inside an async def dependency stalls the event loop for every request. Sharing sessions between sync and async code across threads leads to deadlocks or driver errors.

from collections.abc import AsyncIterator, Iterator

from sqlalchemy import create_engine
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import Session, sessionmaker

# Sync variant: blocking driver (psycopg), plain def, so FastAPI runs it in the threadpool
sync_engine = create_engine("postgresql+psycopg://app:change-me@db:5432/app")
SyncSessionLocal = sessionmaker(sync_engine, expire_on_commit=False)

def get_session() -> Iterator[Session]:
    session = SyncSessionLocal()
    try:
        yield session        # the endpoint runs here; its exceptions are raised at this line
        session.commit()     # reached only if the endpoint finished without raising
    except Exception:
        session.rollback()
        raise                # re-raise so the client sees the real error, not a false success
    finally:
        session.close()      # always return the connection to the pool

# Async variant: async-native driver (asyncpg), async def, runs on the event loop
async_engine = create_async_engine("postgresql+asyncpg://app:change-me@db:5432/app")
AsyncSessionLocal = async_sessionmaker(async_engine, expire_on_commit=False)

async def get_async_session() -> AsyncIterator[AsyncSession]:
    session = AsyncSessionLocal()
    try:
        yield session
        await session.commit()
    except Exception:
        await session.rollback()
        raise
    finally:
        await session.close()

Sync and async SQLAlchemy yield dependencies that commit after a successful endpoint, roll back and re-raise on error, and always close the session, with each session type paired with a matching driver.

How do you structure services and repositories as dependencies?

The session dependency from the previous section becomes the root of a small graph. A repository declares the session as its input, a service declares the repository, settings and current user, and the endpoint declares only the service. FastAPI resolves the graph per request and, because Depends caches results within a request by default, every layer receives the same session object.

request
  └─ endpoint(service)
       └─ OrderService(repo, settings, user)
            ├─ OrderRepository(session) ──┐
            ├─ get_settings()             │
            └─ get_current_user(session) ─┤
                                          ▼
                              get_session()  ← resolved once, shared

Classes work directly as dependencies. Depends(OrderRepository) makes FastAPI read the constructor's parameters and resolve each one, so the class signature is also its wiring. No separate factory function is needed.

For parametrized checks, use a callable instance. A RequireScope class stores a scope in __init__, and its __call__ method declares user = Depends(get_current_user). Then Depends(RequireScope("orders:write")) produces one reusable check per scope.

Some concerns produce no value the handler needs, such as auth gates or rate limits. Attach those with dependencies=[...] at one of three levels:

  • App level: on FastAPI(), for every route.
  • Router level: on APIRouter, for a group of routes.
  • Endpoint level: on the path decorator, for a single route.

FastAPI runs these dependencies and discards their return values.

The payoff is locality. Endpoints shrink to a few lines that parse input and call a service method. Wiring is declared in signatures, so you can find it in one place. Replacing the repository's query logic or adding a cache to the service changes one class, and no endpoint changes.

from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import select
from sqlalchemy.orm import Session
from app.deps import Settings, User, get_current_user, get_session, get_settings
from app.models import Order

class OrderRepository:
    # The constructor signature is the wiring: FastAPI injects the request's session.
    def __init__(self, session: Annotated[Session, Depends(get_session)]):
        self.session = session

    def list_for(self, user_id: int, limit: int) -> list[Order]:
        stmt = select(Order).where(Order.user_id == user_id).limit(limit)
        return list(self.session.scalars(stmt))

class OrderService:
    # Depends() with no argument resolves the annotated class itself.
    def __init__(self, repo: Annotated[OrderRepository, Depends()],
                 settings: Annotated[Settings, Depends(get_settings)],
                 user: Annotated[User, Depends(get_current_user)]):
        self.repo, self.settings, self.user = repo, settings, user

    def recent_orders(self) -> list[Order]:
        return self.repo.list_for(self.user.id, limit=self.settings.page_size)

class RequireScope:
    # One instance per scope; __call__ is what FastAPI runs on each request.
    def __init__(self, scope: str):
        self.scope = scope

    def __call__(self, user: Annotated[User, Depends(get_current_user)]) -> None:
        if self.scope not in user.scopes:
            raise HTTPException(status.HTTP_403_FORBIDDEN, f"missing scope {self.scope}")

# Router-level side-effect check; FastAPI(dependencies=[...]) would apply app-wide.
router = APIRouter(prefix="/orders", dependencies=[Depends(RequireScope("orders:read"))])

@router.get("/")
def list_orders(service: Annotated[OrderService, Depends()]):
    return service.recent_orders()  # endpoint stays thin: no session or query code

A class-based repository and service share one cached request session, while a callable RequireScope instance gates the router through dependencies=.

How do you test FastAPI dependencies with dependency_overrides?

Because app.dependency_overrides is a plain dictionary consulted at resolution time, a test can swap any dependency without changing route code. For database tests, open a connection, begin a transaction on it, and bind a session to that connection. Configure the session so its commits become savepoints rather than ending the outer transaction. Then override get_session with a function that yields this session. The routes and the yield dependency's commit logic run unchanged. At teardown you roll back the outer transaction, so every test starts from the same schema state and nothing has to be truncated or reseeded.

Services work the same way. If routes depend on get_order_service, map that key to a function that returns an in-memory fake with the same methods. Handler tests can then assert on HTTP behaviour and never touch a database.

Overrides are keyed by the original callable, not by its name. The test must import the exact function object that appears in Depends(...). A wrapper with the same name will not match, and neither will a function imported from a module that redefines it. When a key doesn't match, the real dependency runs and no error is raised.

The dictionary is also global state on the app object. An override that one test sets and never removes stays active for every test that runs after it. Tests that run concurrently against one shared app will overwrite each other's entries. Both problems show up as order-dependent, flaky failures. Use a fixture that yields the app and calls app.dependency_overrides.clear() afterward. If tests run in parallel, give each worker its own app instance.

Once the fixtures exist, each new test needs only a line or two of setup. Tests are then quick to write, and they keep working when the internals of a service change.

When should you avoid relying on Depends for sessions and services?

Request-scoped Depends works well for short, database-bound handlers. It works less well once a request does other things.

Teardown timing is not fixed. FastAPI releases have changed when code after yield runs relative to sending the response, running background tasks and streaming a body. Check how the version you run behaves. In background tasks and streaming generators, open a fresh session rather than assuming the request's session is still open. Teardown also brings a second risk: if you commit there, the commit can fail after the response has already been built, so the client sees success for data that was never written.

Caching couples dependencies. Within one request, every dependency that asks for the session receives the same instance. That means one transaction, and a rollback triggered by one service undoes the other's work. The opposite mistake is setting use_cache=False on the session dependency, which silently opens a second session and a second transaction.

Deep graphs hide cost. A handler whose signature looks simple can trigger database-backed auth lookups and other per-request work several layers down.

Connections are held too long. The session keeps a pooled connection for the whole request, including slow external calls. Under load this exhausts the pool. Narrower session scopes release connections sooner, but you give up the simplicity of one transaction per request.

Pitfall Symptom Mitigation
Teardown timing Closed-session errors in background or streaming code Open a new session there
Commit in teardown Client sees success, data missing Commit in the service before returning
Shared cached session One rollback undoes unrelated writes Make transaction ownership explicit
use_cache=False Writes invisible across services Keep the session dependency cached
Deep graphs Unexplained per-request queries Trace and flatten auth chains
Long-held connection Pool timeouts under load Scope sessions around database work

What are the alternatives to FastAPI Depends for wiring services?

Depends only runs when FastAPI handles a request. A background worker consuming a queue, a CLI migration script or a scheduled job never passes through the router, so nothing resolves the dependency graph for them. Those entry points still need the same services, built the same way, which means the wiring has to live somewhere other than route signatures.

Three options come up in practice:

  • Plain factory functions. A function such as one that builds an order service from a session holds the construction logic. Route dependencies call it, and so do workers and scripts, each supplying their own session scope.
  • Module-level globals. A service instantiated at import time is cheap to write. It also shares state across every request and test: a cached session or a mutated config object leaks from one caller into the next, and tests have to patch modules instead of passing arguments.
  • A third-party DI container. These offer scopes and lifecycle hooks beyond HTTP. They also add a second wiring mechanism next to Depends, with its own registration rules and failure modes. When a dependency resolves wrongly, you debug two systems.
Approach Request scoping Use outside HTTP Testability Added complexity
Depends + factories Yes, via yield dependencies Yes, call factories directly High: overrides or plain arguments Low
Module globals No Yes Low: requires patching Very low upfront, high later
DI container Yes, container-defined Yes High High: second system to learn

Start with factory functions. Treat Depends as a thin adapter that calls them for HTTP requests. Add a container only when the factories become hard to manage.

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 shared variable is one edit and one review instead of editing every service's .env by hand.

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.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • 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.