python type_error ai_generated true

fastapi.exceptions.FastAPIError: Invalid args for response field 'depends'

ID: python/fastapi-depends-invalid-parameter

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-04-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

Using `Depends()` incorrectly, such as passing a non-callable or using it in a response model, causes FastAPI to raise an error.

generic

中文

错误使用`Depends()`,如传递非可调用对象或在响应模型中使用,导致FastAPI抛出错误。

Workarounds

  1. 100% success
    Use `Depends()` correctly: `def endpoint(dep: SomeClass = Depends())` or `def endpoint(dep: SomeClass = Depends(get_dep))`.
  2. 95% success
    Ensure the dependency function is callable and has correct signature.

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Using `Depends` as a type hint without parentheses, e.g., `def endpoint(dep: Depends):` fails because Depends is a class, not a type.

  2. 95% fail

    Putting `Depends` in a Pydantic model field doesn't work; it's only for route parameters.