python
data_error
ai_generated
true
fastapi.exceptions.HTTPException: 422: 无法处理的实体
fastapi.exceptions.HTTPException: 422: Unprocessable Entity
ID: python/fastapi-httpexception-422-unprocessable-entity
80%修复率
86%置信度
0证据数
2024-09-12首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
请求体格式正确但包含语义错误,例如无效的数据类型。
English
Request body is well-formed but contains semantic errors, like invalid data types.
解决方案
-
90% 成功率 Use Pydantic's conint or constr for validation
from pydantic import BaseModel, conint class Item(BaseModel): age: conint(gt=0, lt=150) # valid integer -
85% 成功率 Add custom validators
from pydantic import validator class Item(BaseModel): name: str @validator('name') def name_must_be_alpha(cls, v): if not v.isalpha(): raise ValueError('must be alphabetic') return v
无效尝试
常见但无效的做法:
-
Sending numbers as strings without conversion
70% 失败
Pydantic may not auto-convert if strict mode is on.
-
Missing required fields in nested models
80% 失败
Validation fails at nested level.