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
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).
解决方案
-
93% 成功率
import json body = json.dumps({'name': 'x'}) requests.post(url, data=body, headers={'Content-Type': 'application/json'}) -
95% 成功率
requests.post(url, json={'name': 'x'})
无效尝试
常见但无效的做法:
-
85% 失败
Accepting non-JSON violates the API contract.
-
90% 失败
FastAPI then rejects because the endpoint expects a Pydantic body.