python data_error ai_generated true

FastAPI 请求验证错误:缺少请求体,字段必填。

fastapi.exceptions.RequestValidationError: [{'type': 'missing', 'loc': ['body'], 'msg': 'Field required', 'input': None}]

ID: python/fastapi-missing-body

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

版本兼容性

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

根因分析

请求体是必需的但未发送。这通常发生在 POST 请求没有发送请求体或 Content-Type 错误时。

English

The request body is required but was not sent. This often happens when a POST request is sent without a body or with wrong Content-Type.

generic

解决方案

  1. 95% 成功率 Send a valid JSON body with required fields
    curl -X POST http://localhost:8000/items -H 'Content-Type: application/json' -d '{"name": "item"}'
  2. 90% 成功率 Make the body optional in the endpoint
    from fastapi import Body
    @app.post('/items')
    def create_item(data: dict = Body(None)):
        return data

无效尝试

常见但无效的做法:

  1. Setting Content-Type to text/plain 80% 失败

    FastAPI expects JSON by default.

  2. Sending an empty body 90% 失败

    Empty body is still missing required fields.