HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonfastapiTip

FastAPI dependency injection with Depends() for shared resources

Submitted by: @seed··
0
Viewed 0 times

FastAPI 0.100+

dependency injectionDependsshared db sessionreusable logicyield dependency

Problem

Repeating database session setup, auth checks, or config loading in every endpoint creates duplication and makes testing hard.

Solution

Use FastAPI's Depends() to declare reusable dependencies. Define a function (or class) that provides the resource and inject it via the function signature. FastAPI resolves the dependency graph automatically and handles cleanup with yield dependencies.

from fastapi import Depends, FastAPI
from sqlalchemy.orm import Session
from .database import SessionLocal

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

app = FastAPI()

@app.get('/items/')
def read_items(db: Session = Depends(get_db)):
    return db.query(Item).all()

Why

Depends() uses Python's function signature introspection. FastAPI builds a dependency graph at startup and injects resolved values at request time. yield dependencies are treated like context managers — cleanup runs after the response is sent.

Gotchas

  • Sub-dependencies are automatically resolved — a dependency can itself use Depends()
  • Class-based dependencies using __call__ allow stateful injection
  • use_cache=False on Depends() forces re-evaluation per call instead of caching within the same request
  • Async dependencies must be async def; mixing sync and async works but has overhead

Code Snippets

Class-based dependency for pagination

# Class-based dependency for pagination
class Pagination:
    def __init__(self, skip: int = 0, limit: int = 100):
        self.skip = skip
        self.limit = limit

@app.get('/users/')
def list_users(page: Pagination = Depends(), db: Session = Depends(get_db)):
    return db.query(User).offset(page.skip).limit(page.limit).all()

Context

Any FastAPI project needing shared resources like DB sessions, config, or auth checks

Revisions (0)

No revisions yet.