python
data_error
ai_generated
true
fastapi.exceptions.ResponseValidationError: 响应验证错误,返回数据不匹配响应模型。
fastapi.exceptions.ResponseValidationError: 2 validation errors for UserResponse id value is not a valid integer (type=type_error.integer)
ID: python/fastapi-response-validation-error
80%修复率
88%置信度
0证据数
2024-06-07首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 0.100.x | active | — | — | — |
| 0.110.x | active | — | — | — |
根因分析
视图返回的数据不符合声明的 response_model(类型错误、字段缺失或嵌套结构不匹配)。
English
The view returns data that does not conform to the declared response_model (wrong types, missing fields, or extra nested structure).
解决方案
-
95% 成功率
Coerce in the view: `return UserResponse(id=int(user['id']), name=str(user['name']))` or use `.model_validate(user, from_attributes=True)`.
-
90% 成功率
Set `model_config = ConfigDict(from_attributes=True)` on the Pydantic model and return ORM objects directly.
无效尝试
常见但无效的做法:
-
85% 失败
Still logs ResponseValidationError; clients get opaque failures.
-
75% 失败
Loses OpenAPI schema and silently returns wrong shapes.