tezvyn:

How do you use FastAPI dependency injection for database sessions?

AI-drafted, machine-checkedSource: fastapi.tiangolo.comintermediate
How do you use FastAPI dependency injection for database sessions?
WHAT IT TESTS

FastAPI Depends() for session lifecycle and testability.

ANSWER OUTLINE

Build a generator dependency that yields a session and closes it after; inject via Depends(get_db).

WHAT THIS TESTS: 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.

A GOOD ANSWER COVERS: 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.

COMMON WRONG ANSWERS: 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.

LIKELY FOLLOW-UPS: 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.

ONE 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.

Source: fastapi.tiangolo.com

Read the original → fastapi.tiangolo.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.