Concepts 🚀 Project 🧮 Labs
📚 Learn / Web & FastAPI / Dependency injection (Depends)

Dependency injection (Depends)

Share setup logic across routes. get_db is a dep that opens a DB session per request.

Code example

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

@router.get('/x')
async def handler(db: Session = Depends(get_db)):
    return db.query(Model).all()

How it works

FastAPI's dependency injection lets you factor out setup/teardown logic. `Depends(get_db)` runs `get_db()` before the route, injects the yielded value as `db`, and runs the cleanup (db.close()) after the route returns — even on exception. This gives you per-request DB sessions without manual try/finally in every handler. Dependencies can themselves depend on other dependencies — FastAPI builds a DAG and resolves it in order.

🔍 Where this is used in OpenBenchML Every route that touches the database uses `db: Session = Depends(get_db)`.