python config_error ai_generated true

值错误: 重复的路径操作: GET /items/{item_id}

ValueError: Duplicate path operation: GET /items/{item_id}

ID: python/fastapi-path-operation-conflict

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

版本兼容性

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

根因分析

FastAPI中定义了多个相同HTTP方法和路径的路由。

English

FastAPI中定义了多个相同HTTP方法和路径的路由。

generic

解决方案

  1. 95% 成功率 确保每个路径和方法组合唯一
    @app.get('/items/{item_id}') async def read_item(item_id: int): return {'item_id': item_id}; @app.post('/items/{item_id}') async def update_item(item_id: int): return {'updated': item_id}
  2. 90% 成功率 使用不同的路径或添加版本前缀
    @app.get('/v1/items/{item_id}') async def read_item_v1(item_id: int): return {'item_id': item_id}

无效尝试

常见但无效的做法:

  1. 尝试覆盖路由而不删除旧路由 90% 失败

    FastAPI不允许重复注册。

  2. 使用不同的函数名但相同的路径和方法 80% 失败

    路径和方法是唯一标识。