python config_error ai_generated true

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

ID: python/fastapi-multiple-body-params

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-07-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

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

generic

中文

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

Workarounds

  1. 95% success 将多个模型合并为一个嵌套模型
    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% success 使用Body参数分别标注
    from fastapi import Body; @app.post('/create') async def create(item: Item = Body(...), user: User = Body(...)): return {'item': item, 'user': user}

Dead Ends

Common approaches that don't work:

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

    合并后字段名冲突。

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

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