python data_error ai_generated true

HTTP 422 无法处理的实体:请求体字段类型验证失败。

HTTP/1.1 422 Unprocessable Entity {"detail":[{"loc":["body","age"],"msg":"value is not a valid integer","type":"type_error.integer"}]}

ID: python/fastapi-422-unprocessable-entity

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

版本兼容性

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

根因分析

客户端发送的值与 Pydantic 字段类型不匹配(例如给 int 传字符串,给非可选字段传 null)。

English

Client sent a value whose type does not match the Pydantic field (e.g., string for int, null for non-optional).

generic

解决方案

  1. 95% 成功率
    Use `age: int = Field(..., ge=0)` and document; client should send `{"age": 30}` not `{"age": "30"}` unless using `model_config = ConfigDict(coerce_numbers_to_str=False)` with custom validator.
  2. 90% 成功率
    Add a custom validator: `@field_validator('age', mode='before') def coerce(cls, v): return int(v)`

无效尝试

常见但无效的做法:

  1. 90% 失败

    Validation runs before the handler; decorator status does not apply.

  2. 70% 失败

    Hides the real cause; clients still send wrong types.