python type_error ai_generated true

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

ID: python/fastapi-duplicate-route-registration

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-04-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

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

中文

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

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 80% fail

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

  2. 90% fail

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