python
data_error
ai_generated
true
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
80%Fix Rate
88%Confidence
0Evidence
2024-12-02First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 0.100.x | active | — | — | — |
| 0.110.x | active | — | — | — |
Root Cause
Client sent a value whose type does not match the Pydantic field (e.g., string for int, null for non-optional).
generic中文
客户端发送的值与 Pydantic 字段类型不匹配(例如给 int 传字符串,给非可选字段传 null)。
Workarounds
-
95% success
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. -
90% success
Add a custom validator: `@field_validator('age', mode='before') def coerce(cls, v): return int(v)`
Dead Ends
Common approaches that don't work:
-
90% fail
Validation runs before the handler; decorator status does not apply.
-
70% fail
Hides the real cause; clients still send wrong types.