python data_error ai_generated true

fastapi.exceptions.HTTPException: 422: 无法处理的实体

fastapi.exceptions.HTTPException: 422: Unprocessable Entity

ID: python/fastapi-httpexception-422-unprocessable-entity

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

版本兼容性

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

根因分析

请求体格式正确但包含语义错误,例如无效的数据类型。

English

Request body is well-formed but contains semantic errors, like invalid data types.

generic

解决方案

  1. 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
  2. 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

无效尝试

常见但无效的做法:

  1. Sending numbers as strings without conversion 70% 失败

    Pydantic may not auto-convert if strict mode is on.

  2. Missing required fields in nested models 80% 失败

    Validation fails at nested level.