python runtime_error ai_generated true

fastapi.exceptions.ResponseValidationError:ResponseModel 有 1 个验证错误

fastapi.exceptions.ResponseValidationError: 1 validation error for ResponseModel

ID: python/fastapi-responsevalidationerror

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-05-12首次发现

版本兼容性

版本状态引入弃用备注
0.100.x active
0.110.x active

根因分析

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

English

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

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. 70% 失败

    Loses automatic documentation and validation, not a fix.

  2. 80% 失败

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