python
config_error
ai_generated
true
FastAPI 路由冲突:/items/{item_id} 与 /items/new 冲突
fastapi.routing.APIRoute: Route order conflict: /items/{item_id} conflicts with /items/new
ID: python/fastapi-route-order-conflict
80%修复率
88%置信度
0证据数
2024-03-08首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
FastAPI 中动态路由和静态路由顺序不当,导致动态路由捕获了静态路径。
English
FastAPI 中动态路由和静态路由顺序不当,导致动态路由捕获了静态路径。
解决方案
-
95% 成功率
@app.get('/items/new') async def new_item(): ... @app.get('/items/{item_id}') async def get_item(item_id: int): ... -
90% 成功率
@app.get('/items/{item_id:\\d+}') async def get_item(item_id: int): ...
无效尝试
常见但无效的做法:
-
50% 失败
如果业务需要这两个路径,忽略会导致功能缺失。
-
60% 失败
FastAPI 按定义顺序匹配,交换后可能仍冲突。