tiangolo/fastapi · error · DependencyScopeError
The dependency "{call_name}" has a scope of "request", it ca
Error message
The dependency "{call_name}" has a scope of "request", it cannot depend on dependencies with scope "function". What it means
DependencyScopeError raised at dependencies/utils.py:314 during dependency-graph construction. FastAPI forbids a 'request'-scoped dependency that is a generator/async-generator from depending on a 'function'-scoped sub-dependency, because function-scoped deps are resolved per call while request-scoped generator deps live for the whole request — mixing them would tear down the sub-dependency at the wrong time. The check fires in get_dependant when _get_computed_scope(dependant)=='request' and param_details.depends.scope=='function' for a gen/async-gen callable.
Source
Thrown at fastapi/dependencies/utils.py:314
param_details = analyze_param(
param_name=param_name,
annotation=param.annotation,
value=param.default,
is_path_param=is_path_param,
)
if param_details.depends is not None:
assert param_details.depends.dependency
if (
(
_is_gen_callable(dependant.call)
or _is_async_gen_callable(dependant.call)
)
and _get_computed_scope(dependant=dependant) == "request"
and param_details.depends.scope == "function"
):
assert dependant.call
call_name = getattr(dependant.call, "__name__", "<unnamed_callable>")
raise DependencyScopeError(
f'The dependency "{call_name}" has a scope of '
'"request", it cannot depend on dependencies with scope "function".'
)
sub_own_oauth_scopes: list[str] = []
if isinstance(param_details.depends, params.Security):
if param_details.depends.scopes:
sub_own_oauth_scopes = list(param_details.depends.scopes)
sub_dependant = get_dependant(
path=path,
call=param_details.depends.dependency,
name=param_name,
own_oauth_scopes=sub_own_oauth_scopes,
parent_oauth_scopes=current_scopes,
use_cache=param_details.depends.use_cache,
scope=param_details.depends.scope,
)
dependant.dependencies.append(sub_dependant)
continueView on GitHub (pinned to 42a41db11f)
Solutions
- Make the sub-dependency request-scoped too: Depends(..., scope='request') so both share the same lifecycle.
- Or remove the generator (yield) from the outer dependency so it can be function-scoped and depend on function-scoped deps.
- Restructure so the function-scoped dependency is not nested under the request-scoped generator — call it from the path operation directly.
- Audit the dependency tree and align scopes top-down (request deps may only depend on request-scoped deps).
Example fix
# before
def get_db():
with Session() as s:
yield s
def settings = Depends(get_config, scope='function')
def session = Depends(get_db, scope='request') # depends on settings indirectly -> error
# after
def get_db():
with Session() as s:
yield s
def session = Depends(get_db, scope='request')
def settings = Depends(get_config, scope='request') # align scope Defensive patterns
Strategy: validation
Validate before calling
def assert_scope_compatible(outer_scope: str, outer_is_gen: bool, sub_scope: str):
if outer_scope == 'request' and outer_is_gen and sub_scope == 'function':
raise ValueError('request-scoped generator cannot depend on function-scoped dep') Try / catch
from fastapi.exceptions import DependencyScopeError
try:
app = FastAPI()
app.include_router(router) # builds dependency trees
except DependencyScopeError as e:
print('align dependency scopes:', e) Prevention
- Keep dependency scopes consistent: request-scoped generators may only depend on request-scoped deps.
- Avoid mixing scope='function' sub-deps under scope='request' generators.
- Run app import in CI to catch this at build time, not request time.
- Document each dependency's intended scope in its docstring.
When it happens
Trigger: A request-scoped dependency (Depends(..., scope='request')) that is itself a generator (yield), depending via Depends() on another dependency declared with scope='function' (the default). The error is raised while building the route's dependency tree, so it surfaces at app-import/startup, not at request time.
Common situations: Adding scope='request' to a session/get_db generator that itself Depends on a function-scoped helper; upgrading FastAPI and adopting explicit scopes inconsistently; refactoring a shared dependency to generator form without bumping its dependents' scopes.
Related errors
- X-Token header invalid
- No Jessica token provided
- X-Token header invalid
- X-Key header invalid
- X-Token header invalid
AI-assisted analysis of tiangolo/fastapi@42a41db11f (2026-08-04).
Data as JSON: /data/errors/34ae2121b11055fb.json.
Report an issue: GitHub.