python runtime_error ai_generated true

断言错误:重复的路径参数:'item_id'

AssertionError: Duplicate path parameter: 'item_id'

ID: python/fastapi-route-duplicate-path

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

版本兼容性

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

根因分析

FastAPI路由中定义了相同名称的路径参数,导致参数冲突

English

FastAPI路由中定义了相同名称的路径参数,导致参数冲突

generic

解决方案

  1. 95% 成功率 重命名其中一个路径参数
    @app.get('/items/{item_id}')
    @app.get('/items/{other_id}')
  2. 90% 成功率 合并为单个路由并处理不同逻辑
    @app.get('/items/{item_id}')
    async def read_item(item_id: int): pass

无效尝试

常见但无效的做法:

  1. 尝试更改路由顺序而不修改参数名 50% 失败

    参数名重复是根本问题,顺序无关

  2. 使用不同的HTTP方法但保留相同参数名 30% 失败

    参数名冲突发生在同一路由组内