FastAPI: From Basics to Production · Dependency Injection in Depth
Dependencies with yield: Sessions and Resources
Manage per-request resources with setup and teardown.
Dependencies that yield run setup code before the request and teardown after it — ideal for database sessions, transactions and locks. Wrap the yield in try/except/finally to roll back on errors. Treat these resources as request-scoped: the exact moment teardown runs relative to sending the response has changed between FastAPI versions, so never rely on a request's session inside background tasks — open a new session in the task instead.
from collections.abc import AsyncIterator
from sqlalchemy.ext.asyncio import AsyncSession
async def get_db() -> AsyncIterator[AsyncSession]:
async with SessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
DB = Annotated[AsyncSession, Depends(get_db)]
Common pitfalls
- Swallowing exceptions in the teardown (always re-raise).
- Using the request's session inside BackgroundTasks after the response.
- Committing in every repository method instead of once per unit of work.
Key points
- yield = setup + teardown per request
- Rollback on errors and re-raise
- Don't reuse request resources in background tasks
Further reading: FastAPI: Dependencies with yield
Go deeper: FastAPI and Starlette: Middleware, Exceptions and Dependencies in the Request Lifecycle course traces this step of the request, with a production bug and a runnable simulation.
Practice questions
Why must a yield dependency re-raise exceptions it catches?
Answer
So FastAPI's exception handlers can produce the right error response; swallowing them hides failures and may return success incorrectly.
Why shouldn't a background task use the request's database session?
Answer
The session is request-scoped: its teardown (commit/close) is tied to the request lifecycle, so a task running after the response may see a closed or already-committed session. Open a new session inside the task.
Open in the app to mark lessons complete, take notes and track your progress.