python
network_error
ai_generated
true
FastAPI HTTP异常: 422 不可处理的实体
fastapi.exceptions.HTTPException: 422 Unprocessable Entity
ID: python/fastapi-missing-content-type
80%修复率
86%置信度
0证据数
2024-05-30首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
FastAPI请求体为JSON但缺少Content-Type头,导致验证失败。
English
FastAPI请求体为JSON但缺少Content-Type头,导致验证失败。
解决方案
-
95% 成功率 确保客户端发送正确的Content-Type头
requests.post(url, json={'key': 'value'}) # 自动设置Content-Type: application/json -
85% 成功率 使用中间件检查并设置默认Content-Type
from starlette.middleware.base import BaseHTTPMiddleware; class ContentTypeMiddleware(BaseHTTPMiddleware): async def dispatch(self, request, call_next): if not request.headers.get('Content-Type'): request.headers.__dict__['_list'].append(('content-type', 'application/json')); return await call_next(request)
无效尝试
常见但无效的做法:
-
忽略Content-Type头,期望框架自动检测
90% 失败
FastAPI严格依赖Content-Type头。
-
在路由中使用request.json()手动解析
80% 失败
仍然需要Content-Type头。