← Back to FastAPI, page 1

fastapi-0019 · Medium mid

How do dependencies with yield work in FastAPI, for example to manage a database session?

A dependency that uses yield runs the code before yield as setup, injects the yielded value, and runs the code after yield as teardown once the response is ready. Wrapping yield in try/finally guarantees cleanup, and try/except lets you roll back on errors. In current FastAPI the exit code runs after the response is sent (scope="request", the default since 0.118), Depends(..., scope="function") (0.121+) closes it right after the endpoint returns, and since 0.110 an exception you catch after yield must be re-raised.

Full answer

Some resources need cleanup: a database session must be closed, a transaction committed or rolled back, a temporary file deleted. A yield dependency handles both ends:

python
def get_db():
    db = SessionLocal()
    try:
        yield db
        db.commit()
    except Exception:
        db.rollback()
        raise
    finally:
        db.close()

The lifecycle per request:

  1. FastAPI runs the code up to yield.
  2. The yielded value is injected into the endpoint (and other dependencies).
  3. The endpoint runs.
  4. FastAPI resumes the generator: the code after yield runs. If the endpoint raised, the exception is thrown into the generator at the yield line, so except blocks can react.

Version details that matter (this behaviour changed several times):

  • 0.106.0 moved the exit code to run before the response was sent, to release resources sooner. That broke StreamingResponse bodies that still needed the session.
  • 0.110.0: if you catch an exception in a yield dependency and do not re-raise it, FastAPI raises a server error. Re-raise (or raise an HTTPException) so the real error is handled.
  • 0.118.0 went back to running the exit code after the response is sent, so streaming responses can keep using the resource. This is the default, called scope="request".
  • 0.121.0 added Depends(get_db, scope="function"), which runs the exit code right after the endpoint returns, before the response is sent. Use it when you want the connection back in the pool as early as possible.
  • With the default scope, background tasks run before the dependency's exit code (the snippet prints the order). Long background jobs should still open their own session so a slow task does not hold the request's connection.
  • An HTTPException raised in the exit code cannot change a response that has already been sent. The same applies to a failed commit() in a request-scoped dependency: the client may already have its 200. When the client must know whether the write succeeded, commit inside the endpoint or service function (or give the session dependency scope="function").

Rules:

  • Use try/finally for cleanup that must always happen.
  • Keep commit/rollback in one place (the dependency) or in service functions, not both.
  • Sync generator dependencies run in the thread pool; async ones (async def ... yield) run on the event loop. Use async ones with async libraries.
  • Each request gets its own instance, and within a request the value is cached, so the endpoint and other dependencies share the same session.
python
from fastapi import BackgroundTasks, Depends, FastAPI, HTTPException
from fastapi.testclient import TestClient

app = FastAPI()
events = []


class FakeSession:
    def __init__(self):
        self.pending = []
        events.append("open")

    def add(self, row):
        self.pending.append(row)

    def commit(self):
        events.append(f"commit {self.pending}")

    def rollback(self):
        events.append("rollback")

    def close(self):
        events.append("close")


def get_db():
    db = FakeSession()
    try:
        yield db
        db.commit()
    except Exception:
        db.rollback()
        raise
    finally:
        db.close()


def get_audit_log():
    events.append("audit open")
    try:
        yield events
    finally:
        events.append("audit close")


@app.post("/attendance/{roll_no}")
def mark(roll_no: int, background_tasks: BackgroundTasks, db: FakeSession = Depends(get_db),
         log: list = Depends(get_audit_log, scope="function")):
    background_tasks.add_task(events.append, "background task")
    if roll_no > 60:
        raise HTTPException(status_code=404, detail="No such roll number")
    db.add(roll_no)
    return {"marked": roll_no}


c = TestClient(app)
print(c.post("/attendance/7").json(), events)
events.clear()
print(c.post("/attendance/99").status_code, events)

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. FakeSession stands in for a SQLAlchemy Session so the lifecycle is visible. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): {'marked': 7} ['open', 'audit open', 'audit close', 'background task', 'commit [7]', 'close'] 404 ['open', 'audit open', 'audit close', 'rollback', 'close']

Key points

  • Code before yield is setup; after yield is teardown
  • try/except/finally around yield handles commit, rollback, close
  • Exceptions from the endpoint are thrown into the generator
  • Re-raise caught exceptions (required since 0.110)
  • Default scope='request' exits after the response; scope='function' exits right after the endpoint (0.121+)

Common mistakes

  • Forgetting finally, so sessions leak when the endpoint raises
  • Catching exceptions after yield and not re-raising them
  • Reusing the request's database session inside a background task
  • Committing in both the dependency and the endpoint
  • Committing in a request-scoped exit step and assuming a commit failure will reach the client

Follow-ups

  • Why did FastAPI move the exit code of yield dependencies back to after the response in 0.118?
  • How would you share one transaction across several dependencies in a request?
  • When would you use an async generator dependency?

Tips

  • Walk through the four steps of the lifecycle
  • Show commit, rollback and close in the right places
  • Mention the version changes; it shows you keep up