python data_error ai_generated true

fastapi.exceptions.RequestValidationError: Model 的 1 个校验错误 body -> age 不是有效的整数 (type=type_error.integer)

fastapi.exceptions.RequestValidationError: 1 validation error for Model body -> age value is not a valid integer (type=type_error.integer)

ID: python/fastapi-pydantic-validation-int-parsing

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

版本兼容性

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

根因分析

Pydantic 的 int 字段从 JSON 请求体接收到非数字字符串或带小数的浮点数。

English

A Pydantic int field receives a non-numeric string or float with fractional part from the JSON body.

generic

解决方案

  1. 92% 成功率
    requests.post(url, json={'age': int(age_str)})
  2. 90% 成功率
    from pydantic import field_validator
    @field_validator('age', mode='before')
    def parse_age(cls, v):
        return int(v)

无效尝试

常见但无效的做法:

  1. 80% 失败

    Downstream arithmetic fails with TypeError.

  2. 85% 失败

    Hides bad data and corrupts records.