Async Dependencies
FastAPI fully supports asynchronous dependencies, which is essential for I/O-bound operations like database queries or API calls.Basic Async Dependency
Async dependencies are only resolved when used in async path operations. In sync path operations, they’re executed in a threadpool.
Mixing Async and Sync Dependencies
You can mix async and sync dependencies freely:Dependency Caching
By default, FastAPI caches dependency results within a single request. This prevents expensive operations from running multiple times.How Caching Works
Cache Keys
Dependencies are cached based on:- The dependency callable itself
- OAuth2 scopes (if using Security)
- The dependency scope (function or request)
fastapi/dependencies/models.py:63-71 for the cache key implementation.
Disabling Cache
Disable caching for dependencies that must run every time:Generator Dependencies with Cleanup
Generator dependencies (usingyield) enable setup and teardown logic, perfect for managing resources.
Basic Generator Dependency
yield executes after the response is sent, ensuring proper cleanup even if exceptions occur.
Async Generator Dependencies
Exception Handling in Dependencies
Dependency Scopes
Dependencies can have different scopes that control their lifecycle:Function Scope
Function-scoped dependencies are created and destroyed with each path operation function:scope="function" is required when using generator dependencies with streaming responses. The dependency remains active until the generator completes.Request Scope
Request-scoped dependencies (the default for generators) are tied to the request lifecycle:Scope Rules
- Regular (non-generator) dependencies have no scope
- Generator dependencies default to
scope="request" - Function-scoped dependencies can only depend on other function-scoped dependencies
- Request-scoped dependencies cannot depend on function-scoped dependencies
fastapi/dependencies/utils.py:315-326 for scope validation.
Advanced Patterns
Class-Based Dependencies
Create reusable dependency classes:Parameterized Dependencies
Create dependency factories:Nested Dependencies with Context
Best Practices
Generator cleanup is guaranteed: Code after
yield always executes, even if the path operation raises an exception.See Also
- Dependency Overrides - Testing with dependency overrides
- Dependencies in path operation decorators - FastAPI docs
- Dependencies with yield - FastAPI docs