python data_error ai_generated true

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-07-27First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

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

generic

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 80% fail

    Downstream arithmetic fails with TypeError.

  2. 85% fail

    Hides bad data and corrupts records.