python data_error ai_generated true

fastapi.exceptions.RequestValidationError: ItemCreate 有 1 个验证错误 body -> name 字段缺失 (type=value_error.missing)

fastapi.exceptions.RequestValidationError: 1 validation error for ItemCreate body -> name field required (type=value_error.missing)

ID: python/fastapi-422-field-required-body

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

版本兼容性

版本状态引入弃用备注
0.100+ active — — —

根因分析

客户端发送的 JSON 请求体缺少 Pydantic 模型声明为必需(无默认值)的字段。

English

Client sent a JSON body missing a field that the Pydantic model declares as required (no default).

generic

解决方案

  1. 92% 成功率
    from typing import Optional
    class ItemCreate(BaseModel):
        name: Optional[str] = None
  2. 95% 成功率
    requests.post(url, json={'name': 'x', 'price': 1.0})  # include all required fields

无效尝试

常见但无效的做法:

  1. 95% 失败

    Response model affects serialization, not request validation.

  2. 80% 失败

    Validation runs before your middleware can bypass it; also disables all validation.