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 IT TESTS: Whether you understand FastAPI dependency injection for session lifecycle and testability. ANSWER OUTLINE: Create a generator dependency that yields a session and closes it in a finally block after the request; inject it with Depends(get_db). This centralizes connection handling, prevents leaks, and lets you override the dependency in tests. RED FLAG: Treating DI as mere syntactic sugar, omitting yield cleanup, or suggesting a global shared session that breaks under concurrency.
Read the original → fastapi.tiangolo.com
- #fastapi
- #dependency-injection
- #python
- #databases
- #sqlalchemy
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.