How do you use FastAPI dependency injection for database sessions?

FastAPI Depends() for session lifecycle and testability.
Build a generator dependency that yields a session and closes it after; inject via Depends(get_db).
What's really being asked
This question probes whether you understand FastAPI's dependency injection as a lifecycle and scoping tool, not just a convenience import. The interviewer wants to see that you know how to use generator dependencies with yield to acquire and reliably release database connections, and that you understand why per-request sessions matter for concurrency safety and testability in production workloads.
The full answer
First, define a generator dependency such as def get_db that creates a SessionLocal, yields the session to the path operation, and closes it afterward, ideally in a finally block. Second, inject that dependency into endpoint functions using Depends(get_db) so FastAPI resolves it automatically for every request. Third, explain that this pattern is preferred because it centralizes session management, eliminates duplicated boilerplate, guarantees cleanup even when exceptions occur, and enables easy testing via dependency_overrides. Fourth, contrast it with manually creating a session inside each endpoint, which scatters cleanup logic, risks connection leaks if close is forgotten, and makes unit testing difficult because the session source is hardcoded inside the path operation.
The mistakes people make
A red flag is treating dependency injection as mere syntactic sugar without mentioning testability or resource cleanup. Another is suggesting a global or singleton session reused across requests, which breaks thread safety and async concurrency in SQLAlchemy and can lead to catastrophic data mixing between users. Candidates also stumble by omitting the yield cleanup phase or confusing the dependency with middleware that runs on every request regardless of whether the endpoint needs a database connection.
What usually comes next
Expect the interviewer to ask how you would write tests against this pattern, which should involve app.dependency_overrides[get_db] = override_get_db. They may also ask what happens when an exception is raised inside the endpoint, where the answer is that the code after yield still runs to close the session. A third follow-up might cover async database drivers, in which case you would use an async generator dependency with async def and await, or ask how to handle transactions and rollback behavior on failure.
A concrete example
You write def get_db: db = SessionLocal; try: yield db; finally: db.close. Then in an endpoint like @app.get("/heroes") def read_heroes(db: Session = Depends(get_db)), you use db.query(Hero).all. FastAPI calls get_db for each request, yields a fresh session, executes the endpoint, and runs the finally block to close the connection before sending the response.
Interview question
Why should get_db use yield instead of return when providing a database session to FastAPI endpoints?
- a.Yield allows the session to be defined once globally and imported by all endpoints.
- b.Yield converts the function into middleware that executes for every route automatically.
- c.Yield lets FastAPI cache the session for reuse across multiple incoming requests.
- d.Yield ensures cleanup logic in the finally block runs after the endpoint completes.Correct
Why? this is the answer
Using yield with a finally block guarantees the session closes after the endpoint runs, even if an exception occurs. Reusing a cached session across requests, as in option C, breaks thread safety and causes concurrency issues.
Just read this? Test yourself on what you have been reading.
Read the original → fastapi.tiangolo.com
You just looked this up. Could you explain it out loud?
That is the part interviews actually test. Tezvyn takes questions like this one and gives you what the interviewer is really checking, the answer that lands, and the mistake that ends the conversation, in the four minutes before your next meeting.
The iPhone app is on the way
We are building it. Until it lands, nothing here is held back from you: every interview card, your saved cards, streaks and the job board all work in Safari, plus hundreds of free practice quizzes of thirty questions each. Sign in and it all carries over to the app the day it arrives.
Want it as an icon? Tap Share at the bottom of Safari, then Add to Home Screen. It opens full screen and the cards you have read stay available offline.
We are hiring for this. Open roles that interview on fastapi — each one lists the topics its interview covers.
See open roles