Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 50 ยท Dependency injection

Class and yield dependencies

Use classes as FastAPI dependencies, write yield dependencies for setup and teardown, see how errors reach cleanup code, and know how long each resource lives.

In Dependencies every dependency was a plain function that returned a value. Two more shapes cover the rest of real life. A class can be a dependency when you want parameters grouped into an object with behavior. And a function that uses yield instead of return can run code before the endpoint (setup) and after it (teardown), which is exactly what you need for database sessions, file handles and transactions.

This lesson shows both, with output you can run. You will also learn what happens to your cleanup code when the endpoint fails, and how long a dependency's value stays alive.

Classes as dependencies

FastAPI only needs a callable. A class is callable: calling it creates an instance. So Depends(Pagination) means "create a Pagination object for this request", and FastAPI reads the parameters of __init__ the same way it reads a function's parameters, with the same validation and the same entries in the docs.

Why prefer a class? You get attributes, properties and methods on the injected object. Editors can autocomplete p.offset, which is nicer than digging in a dictionary.

When the annotation is already the class, you can write Depends() with nothing inside, and FastAPI uses the annotated type. Combined with Annotated you can name the whole thing once:

Python
PageDep = Annotated[Pagination, Depends()]

@app.get("/books")
async def books(p: PageDep): ...

There is a second class pattern: an instance that is callable. Define __call__, configure the object when you create it, and pass the instance to Depends. That is perfect for a dependency with settings, such as "allow only these roles". Each configured instance is a different dependency, so you can create only_staff and only_owner from one class.

Python A class dependency and a configurable callable instance

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

/books?page=2&size=5 gives offset 5: the class read page and size from the query string, and the endpoint used its offset property. For /staff the instance only_staff carries its allowed roles, while role still comes from the request.

The shim at the top of the example exists only because the browser runtime cannot start threads. A plain function or class (not async) is normally executed in a worker thread so it cannot block the event loop; here we run it inline instead. On your own machine you do not need those lines. The note in async def vs def endpoints explains the thread rule.

yield: setup before, cleanup after

A dependency that uses yield is a generator. FastAPI runs the code up to yield, passes the yielded value to the endpoint, and, once the endpoint is done, resumes the generator so the code after yield can clean up. The pattern is the same as a context manager, and it behaves the same way: wrap the yield in try/finally so the cleanup runs no matter what.

sequenceDiagram
    participant F as FastAPI
    participant D as Dependency
    participant E as Endpoint
    F->>D: run until yield
    D-->>F: resource
    F->>E: call with resource
    E-->>F: return value (or exception)
    F->>D: resume after yield
    D->>D: finally block closes the resource

The code before yield is setup, the code after it (in finally) is teardown.

Typical jobs: open a database session and close it, open a connection and release it back to a pool, acquire a lock, start a timer, begin a transaction.

Python Teardown runs on success and on errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Compare the two logs. On the happy path you see open, the endpoint, after endpoint, close. On the failing path the line after endpoint is missing, but close is still there. When the endpoint raises, the exception is thrown into the generator at the yield line, so everything after yield that is not in finally is skipped. The lesson: put cleanup in finally, and put "success only" work (like a commit) after the yield inside try.

Reacting to errors

Because the exception arrives at the yield, you can catch it. A transaction is the classic example: commit if the endpoint succeeded, roll back if it raised.

Python A transaction dependency: commit or roll back

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Paying 40 commits; paying 400 rolls back and the client still receives the 402. Notice the bare raise after the rollback. If you catch an exception in a yield dependency, re-raise it (or raise a different one) unless you truly want to swallow it. Swallowing it would hide the failure from FastAPI's error handling, and the client would not get the response you intended.

Do not do slow, important work in the teardown that the client is waiting for, and never rely on teardown to deliver user-visible results. Teardown is for releasing resources. If you need to do work after responding, use background tasks.

How long does a dependency live?

A dependency's value lives for one request. FastAPI creates it when the request needs it, shares it with every part of the same request (the per-request cache from the previous lesson), and finishes the teardown when the endpoint is done. The next request starts from scratch. That is why a yield dependency is the right home for a database session: each request gets its own, and it is always closed.

What does not belong in a dependency is state that must outlive a request, such as a connection pool or a loaded machine-learning model. Create those once when the application starts and keep them on app.state, as shown in Lifespan events and app state. A dependency can then borrow from that shared object for each request.

Need Right tool
Parameters grouped with behavior Class dependency
Configurable, reusable check Callable instance (__call__)
Per-request resource with cleanup yield dependency
One resource for the whole app Lifespan + app.state

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Depends() with empty parentheses do when the parameter is annotated with a class?

    FastAPI takes the annotation, here a class, as the callable to use, so Annotated[Pagination, Depends()] means Depends(Pagination).
  2. 2. When does the code after yield in a dependency run?

    The generator is resumed after the endpoint finishes. If the endpoint raised, the exception is thrown in at the yield, so code outside finally is skipped.
  3. 3. You catch an HTTPException in a yield dependency to roll back a transaction. What should you do next?

    Roll back, then raise again so the client still receives the intended error response.
  4. 4. Which resource belongs in app-wide state rather than in a per-request yield dependency?

    A pool is expensive to create and meant to be shared across requests, so it is built once in the lifespan and borrowed per request.

Summary

  • A class works as a dependency because classes are callable; Annotated[Cls, Depends()] uses the annotation itself.
  • A callable instance (__call__) is a configurable dependency: build one per setting.
  • yield dependencies run setup before the endpoint and teardown after; use try/finally for cleanup that must always run.
  • Errors from the endpoint are thrown into the generator at yield; re-raise them after handling.
  • A dependency's value lives for one request; share long-lived resources through the lifespan and app.state.

Next: Router-level and global dependencies applies dependencies to whole groups of endpoints.