python type_error ai_generated true

FastAPI错误:函数中参数名重复

fastapi.exceptions.FastAPIError: Duplicate parameter name: 'item_id' in function 'read_item'

ID: python/fastapi-duplicate-route-registration

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

版本兼容性

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

根因分析

在单个路由处理函数中定义多个同名路径参数(如`@app.get('/items/{item_id}')`并在函数签名中重复使用`item_id`)会导致重复参数错误。

English

Defining multiple path parameters with the same name in a single route handler (e.g., `@app.get('/items/{item_id}')` and then using `item_id` twice in the function signature) causes a duplicate parameter error.

generic

解决方案

  1. 100% 成功率
    Ensure each path parameter appears only once in the function signature. Example: `def read_item(item_id: int, q: str = None):`
  2. 95% 成功率
    Use distinct names for path and query parameters, e.g., `def read_item(item_id: int, query_param: str = None):`

无效尝试

常见但无效的做法:

  1. 80% 失败

    Renaming the parameter in the function signature but not in the path decorator causes a mismatch and still raises an error.

  2. 90% 失败

    Using type hints like `item_id: int` doesn't resolve the duplicate; FastAPI still sees two parameters with the same name.