python runtime_error ai_generated true

fastapi.exceptions.ResponseValidationError: 1 validation error for ResponseModel

ID: python/fastapi-responsevalidationerror

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-05-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.100.x active
0.110.x active

Root Cause

The data returned from the endpoint doesn't match the declared response_model schema.

generic

中文

端点返回的数据与声明的 response_model 模式不匹配。

Workarounds

  1. 90% success
    @app.get('/item', response_model=Item)
    def get_item():
        return {"name": "foo", "price": 10.0}
  2. 85% success
    from typing import Union
    @app.get('/item', response_model=Union[Item, Error])

Dead Ends

Common approaches that don't work:

  1. 70% fail

    Loses automatic documentation and validation, not a fix.

  2. 80% fail

    Only excludes unset fields, doesn't fix type mismatches.