Discover how to make your FastAPI apps handle resources effortlessly and safely with async generator dependencies!
Why Async generator dependencies in FastAPI? - Purpose & Use Cases
Imagine you have a web app that needs to open a database connection for each request, then close it after the response is sent. You try to open and close the connection manually in every route handler.
Manually opening and closing resources in every handler is repetitive and easy to forget. If you forget to close the connection, it can cause memory leaks or locked resources. It's hard to keep your code clean and safe.
Async generator dependencies in FastAPI let you write one function that opens a resource, yields it for use, then automatically cleans it up after. FastAPI handles calling this function for each request, so your routes stay simple and safe.
async def get_db(): db = open_db() return db
async def get_db(): db = await open_db() try: yield db finally: await db.close()
This lets you manage resources like database connections or files cleanly and automatically for each request, avoiding leaks and bugs.
In a FastAPI app, you can use an async generator dependency to open a database session for each web request, then close it right after the response is sent, without repeating code in every route.
Manual resource management is repetitive and error-prone.
Async generator dependencies automate setup and cleanup per request.
This keeps your FastAPI code clean, safe, and easy to maintain.