python network_error ai_generated true

FastAPI HTTP异常: 422 不可处理的实体

fastapi.exceptions.HTTPException: 422 Unprocessable Entity

ID: python/fastapi-missing-content-type

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

版本兼容性

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

根因分析

FastAPI请求体为JSON但缺少Content-Type头,导致验证失败。

English

FastAPI请求体为JSON但缺少Content-Type头,导致验证失败。

generic

解决方案

  1. 95% 成功率 确保客户端发送正确的Content-Type头
    requests.post(url, json={'key': 'value'})  # 自动设置Content-Type: application/json
  2. 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)

无效尝试

常见但无效的做法:

  1. 忽略Content-Type头,期望框架自动检测 90% 失败

    FastAPI严格依赖Content-Type头。

  2. 在路由中使用request.json()手动解析 80% 失败

    仍然需要Content-Type头。