0
0
FastapiHow-ToBeginner · 3 min read

How to Use Yield Dependency in FastAPI for Cleanup Tasks

In FastAPI, use yield inside a dependency function to run setup code before the request and cleanup code after the request finishes. This pattern is useful for managing resources like database connections or sessions that need to be closed after use.
📐

Syntax

A dependency function using yield has two parts: code before yield runs before the request, and code after yield runs after the request completes. The value yielded is passed to the path operation function.

  • def dependency(): defines the dependency function.
  • setup code runs before the request.
  • yield resource provides the resource to the endpoint.
  • cleanup code runs after the request finishes.
python
from fastapi import Depends, FastAPI

app = FastAPI()

def get_resource():
    # Setup code
    resource = "resource ready"
    yield resource
    # Cleanup code
    print("Cleanup after request")

@app.get("/")
async def read_root(resource: str = Depends(get_resource)):
    return {"resource": resource}
💻

Example

This example shows a dependency that simulates opening and closing a database connection. The yield provides the connection to the endpoint, and after the response, the connection is closed automatically.

python
from fastapi import Depends, FastAPI

app = FastAPI()

def get_db():
    print("Opening DB connection")
    db = "db_connection"
    yield db
    print("Closing DB connection")

@app.get("/items/")
async def read_items(db=Depends(get_db)):
    return {"db": db, "items": ["item1", "item2"]}
Output
Opening DB connection # HTTP response: {"db": "db_connection", "items": ["item1", "item2"]} Closing DB connection
⚠️

Common Pitfalls

Common mistakes when using yield dependencies include:

  • Not using yield and returning the resource instead, which skips cleanup.
  • Placing cleanup code before yield, so it runs too early.
  • Forgetting to declare the dependency with Depends() in the endpoint.
python
from fastapi import Depends, FastAPI

app = FastAPI()

# Wrong: returns resource, no cleanup
# def get_resource_wrong():
#     resource = "ready"
#     return resource
#     print("Cleanup never runs")

# Correct:
def get_resource_correct():
    resource = "ready"
    yield resource
    print("Cleanup runs after response")

@app.get("/test")
async def test(resource: str = Depends(get_resource_correct)):
    return {"resource": resource}
📊

Quick Reference

Tips for using yield dependencies in FastAPI:

  • Use yield to separate setup and cleanup logic.
  • Cleanup code runs after the response is sent.
  • Always use Depends() to inject the dependency.
  • Great for managing database sessions, file handles, or external connections.

Key Takeaways

Use yield in FastAPI dependencies to run cleanup code after request completion.
Code before yield runs before the request; code after runs after the response.
Always declare dependencies with Depends() to enable injection.
Yield dependencies are ideal for managing resources like database connections.
Avoid returning resources directly if cleanup is needed; use yield instead.