FastAPI interview question · Most asked

How do `yield` dependencies work and why are they used for database sessions?

Summary

A dependency that yields provides the yielded value to the endpoint and runs the code after yield once the request is done, which suits opening and closing DB sessions or transactions.

Longer Answer

FastAPI wraps the generator like a context manager. Exceptions raised in the endpoint propagate into the dependency at the yield, so you can roll back in except. Exactly when teardown runs relative to sending the response has changed between FastAPI versions, so commit explicitly in your service/endpoint (so commit errors reach the client) and let background tasks open their own sessions instead of reusing the request's.

Code Example

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  # endpoint/service calls `await session.commit()`
        except Exception:
            await session.rollback()
            raise

DbSession = Annotated[AsyncSession, Depends(get_db)]

Key Points

  • Code before yield = setup
  • Code after yield = teardown
  • Catch exceptions to roll back
  • Background tasks should open their own sessions

More most-asked FastAPI questions

← All FastAPI questions