📖 Scenario: You are building a simple FastAPI app that needs to manage a resource using an async generator dependency. This pattern is useful for opening and closing connections or sessions cleanly.
🎯 Goal: Create an async generator dependency that yields a resource string, then use it in a FastAPI route to return the resource.
📋 What You'll Learn
Create an async generator function called get_resource that yields the string 'resource_opened'
Use yield inside get_resource to provide the resource
Create a FastAPI app instance called app
Create a GET route /resource that uses get_resource as a dependency
Return the yielded resource string from the route handler
💡 Why This Matters
🌍 Real World
Async generator dependencies are used in FastAPI to manage resources like database connections, sessions, or files that need setup and cleanup around a request.
💼 Career
Understanding async generator dependencies is important for backend developers working with FastAPI to write clean, efficient, and maintainable code that manages resources properly.
Progress0 / 4 steps
1
Create the async generator dependency
Create an async generator function called get_resource that yields the string 'resource_opened'.
FastAPI
Hint
Use async def to define the function and yield to provide the resource.
2
Create the FastAPI app instance
Import FastAPI from fastapi and create an app instance called app.
FastAPI
Hint
Use from fastapi import FastAPI and then app = FastAPI().
3
Create a GET route using the async generator dependency
Create a GET route /resource using @app.get("/resource"). Define an async function read_resource that takes a parameter resource with a dependency on get_resource using Depends. Return the resource string from the function.
FastAPI
Hint
Use @app.get("/resource") and Depends(get_resource) to inject the dependency.
4
Complete the FastAPI app with dependency injection
Ensure the full code includes the import of Depends, the async generator get_resource, the app instance app, and the GET route /resource that returns the yielded resource string.
FastAPI
Hint
Check that all parts are included and correctly connected.
Practice
(1/5)
1. What is the main purpose of using an async generator dependency in FastAPI?
easy
A. To manage setup and cleanup actions around a request automatically
B. To speed up synchronous code execution
C. To replace all regular functions with asynchronous ones
D. To create infinite loops inside API endpoints
Solution
Step 1: Understand async generator dependencies
Async generator dependencies use async def with yield to run setup code before yielding and cleanup code after.
Step 2: Identify their purpose in FastAPI
This pattern is mainly used to manage resources safely, like opening and closing database connections around a request.
Final Answer:
To manage setup and cleanup actions around a request automatically -> Option A
When the endpoint is called, FastAPI runs the async generator up to the yield (prints 'Setup'), then runs the endpoint code (prints 'Inside endpoint'), then after response finishes, runs code after yield (prints 'Cleanup').
Step 2: Order of prints
The prints happen in order: 'Setup', 'Inside endpoint', 'Cleanup'.
Final Answer:
Setup, Inside endpoint, Cleanup -> Option D
Quick Check:
Yield pauses, so Setup before, Cleanup after endpoint [OK]
Hint: Setup prints before yield, cleanup after endpoint runs [OK]
Common Mistakes:
Assuming cleanup runs before endpoint
Thinking yield returns immediately
Ignoring async generator lifecycle
4. Identify the error in this async generator dependency code:
D. Depends should not be used with async generators
Solution
Step 1: Check resource cleanup safety
Without try-finally, if an exception occurs, await connection.close() might not run, causing resource leaks.
Step 2: Proper pattern for async generator cleanup
Use try-finally around yield to guarantee cleanup runs even on errors.
Final Answer:
Not using try-finally to ensure cleanup -> Option C
Quick Check:
Always use try-finally for cleanup in async generators [OK]
Hint: Use try-finally to guarantee cleanup after yield [OK]
Common Mistakes:
Forgetting try-finally causes resource leaks
Thinking yield needs await
Believing Depends can't use async generators
5. You want to create an async generator dependency that opens a database connection, yields it, and ensures it closes even if the endpoint raises an error. Which code snippet correctly implements this?