python data_error ai_generated true

fastapi.exceptions.HTTPException: 422:无法处理的实体 - json_invalid:JSON 解码错误

fastapi.exceptions.HTTPException: 422: Unprocessable Entity - json_invalid: JSON decode error

ID: python/fastapi-body-not-json

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

版本兼容性

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

根因分析

请求 Content-Type 为 application/json,但请求体是格式错误的 JSON(尾随逗号、单引号、空体)。

English

The request Content-Type is application/json but the body is malformed JSON (trailing comma, single quotes, empty body).

generic

解决方案

  1. 93% 成功率
    import json
    body = json.dumps({'name': 'x'})
    requests.post(url, data=body, headers={'Content-Type': 'application/json'})
  2. 95% 成功率
    requests.post(url, json={'name': 'x'})

无效尝试

常见但无效的做法:

  1. 85% 失败

    Accepting non-JSON violates the API contract.

  2. 90% 失败

    FastAPI then rejects because the endpoint expects a Pydantic body.