FastAPI `yield` Dependencies for Setup and Teardown
A `yield` dependency is a context manager for your endpoints. Code before `yield` runs setup, like getting a DB connection; code after `yield` runs teardown.
WHY IT EXISTS Standard dependencies using return are great for providing values, but they can't manage resources that need cleanup after the request is handled. The yield mechanism was introduced to solve this "setup and teardown" lifecycle problem directly within FastAPI's dependency injection system.
THE MENTAL MODEL Think of a yield dependency as a Python context manager (with open(...) as f:), but for an API request. The code before the yield is the setup phase, like a context manager's __enter__. The code after the yield is the teardown phase, like the __exit__ method, which runs after your endpoint logic is complete.
HOW IT WORKS When you define a dependency with yield, FastAPI executes the code up to the yield statement. The value you yield is injected into your path operation function. FastAPI then pauses the dependency and executes your endpoint. After the response is generated, FastAPI resumes the dependency function, executing the code that comes after the yield. To guarantee cleanup, you should always place your teardown logic inside a try...finally block.
WHEN TO USE IT This pattern is essential for managing resources with a clear open/close or acquire/release lifecycle. Use it for creating and closing database sessions, beginning and committing/rolling back database transactions, or acquiring and releasing locks. It ensures that cleanup happens reliably, even if errors occur in the endpoint.
WHEN NOT TO USE IT If your dependency only calculates and provides a value with no cleanup needed, a simple return is more straightforward. Also, avoid yield dependencies if you think you need to modify the response during the teardown phase. The code after yield runs after the response has been sent, so raising an HTTPException or changing headers will have no effect on the client.
ONE CANONICAL EXAMPLE A database session generator is the classic use case. An async function can create a database session from a connection pool. It then enters a try block and yields the session to the endpoint. The finally block contains the db.close() call, guaranteeing that the session is returned to the pool whether the request succeeded or failed. This prevents connection leaks and keeps your application stable.
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.