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
- When should an endpoint be `async def` versus plain `def` in FastAPI?
- What is FastAPI and what makes it different from Flask or Django?
- Walk through what happens to a request in FastAPI, from the ASGI server to the response.
- How does FastAPI distinguish path, query and body parameters?
- How does FastAPI use Pydantic for request validation?
- What does `response_model` (or a return annotation) do in FastAPI?
- How does dependency injection with `Depends` work in FastAPI?
- How do you implement OAuth2 password flow with JWT in FastAPI?