python type_error ai_generated true

FastAPI 错误:响应字段的参数无效。

fastapi.exceptions.FastAPIError: Invalid args for response field

ID: python/fastapi-multiple-body-parameters

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

版本兼容性

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

根因分析

在未将多个 body 参数嵌入单个 Pydantic 模型的情况下使用它们。

English

Using multiple body parameters without embedding them in a single Pydantic model.

generic

解决方案

  1. 95% 成功率
    class Item(BaseModel):
        name: str
        price: float
    
    @app.post('/item')
    async def create(item: Item):
        return item
  2. 85% 成功率
    Use Body(embed=True) for a single param: async def create(item: str = Body(embed=True))

无效尝试

常见但无效的做法:

  1. 90% 失败

    FastAPI expects a single body; multiple params cause confusion.

  2. 70% 失败

    Loses validation and type safety.