python type_error ai_generated true

fastapi.exceptions.FastAPIError: Invalid args for response field! Hint: check that <class 'models.User'> is a valid Pydantic field type

ID: python/fastapi-route-name-conflict-openapi

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-06-19First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.100.x active — — —
0.110.x active — — —

Root Cause

Passing a non-Pydantic class as response_model, or a Pydantic v1 BaseModel under v2.

generic

中文

将非Pydantic类作为response_model传递,或在v2下使用了Pydantic v1的BaseModel。

Workarounds

  1. 95% success
    class UserOut(BaseModel):\n    id: int\n    name: str
  2. 85% success
    class M(BaseModel):\n    model_config = ConfigDict(arbitrary_types_allowed=True)\n    obj: MyClass

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Removes OpenAPI schema; clients lose type info.

  2. 80% fail

    Pydantic v2 uses __get_pydantic_core_schema__; v1 hook ignored.