python data_error ai_generated true

fastapi.exceptions.HTTPException: 422: Unprocessable Entity

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-09-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

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

generic

中文

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

Workarounds

  1. 90% success 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% success 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

Dead Ends

Common approaches that don't work:

  1. Sending numbers as strings without conversion 70% fail

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

  2. Missing required fields in nested models 80% fail

    Validation fails at nested level.