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:
def get_db():
db = SessionLocal()
try:
yield db
db.commit()
except Exception:
db.rollback()
raise
finally:
db.close()The lifecycle per request:
- FastAPI runs the code up to
yield. - The yielded value is injected into the endpoint (and other dependencies).
- The endpoint runs.
- FastAPI resumes the generator: the code after
yieldruns. If the endpoint raised, the exception is thrown into the generator at theyieldline, soexceptblocks 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
StreamingResponsebodies 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
HTTPExceptionraised in the exit code cannot change a response that has already been sent. The same applies to a failedcommit()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 dependencyscope="function").
Rules:
- Use
try/finallyfor 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.
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