python
network_error
ai_generated
true
fastapi.exceptions.HTTPException: 422 Unprocessable Entity
ID: python/fastapi-missing-content-type
80%Fix Rate
86%Confidence
0Evidence
2024-05-30First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
FastAPI请求体为JSON但缺少Content-Type头,导致验证失败。
generic中文
FastAPI请求体为JSON但缺少Content-Type头,导致验证失败。
Workarounds
-
95% success 确保客户端发送正确的Content-Type头
requests.post(url, json={'key': 'value'}) # 自动设置Content-Type: application/json -
85% success 使用中间件检查并设置默认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)
Dead Ends
Common approaches that don't work:
-
忽略Content-Type头,期望框架自动检测
90% fail
FastAPI严格依赖Content-Type头。
-
在路由中使用request.json()手动解析
80% fail
仍然需要Content-Type头。