python config_error ai_generated true

类型错误: 使用Pydantic模型时不允许有多个body参数。

TypeError: Multiple body parameters are not allowed when using Pydantic models.

ID: python/fastapi-multiple-body-params

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

版本兼容性

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

根因分析

FastAPI路由中定义了多个Pydantic模型作为body参数,但HTTP请求只能有一个body。

English

FastAPI路由中定义了多个Pydantic模型作为body参数,但HTTP请求只能有一个body。

generic

解决方案

  1. 95% 成功率 将多个模型合并为一个嵌套模型
    class Item(BaseModel): name: str; class User(BaseModel): username: str; class Combined(BaseModel): item: Item; user: User; @app.post('/create') async def create(data: Combined): return data
  2. 90% 成功率 使用Body参数分别标注
    from fastapi import Body; @app.post('/create') async def create(item: Item = Body(...), user: User = Body(...)): return {'item': item, 'user': user}

无效尝试

常见但无效的做法:

  1. 尝试合并模型但忽略字段冲突 60% 失败

    合并后字段名冲突。

  2. 使用多个非模型参数(如str)作为body 70% 失败

    FastAPI会将多个参数视为查询参数。