You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI中APIRouter前缀重复问题:原因及解决方法

前缀重复的原因

这个问题是由于fastapi_utils.cbv装饰器的实现机制导致的。当你给APIRouter实例设置prefix参数后,@cbv(router)在装饰类时会错误地将该前缀再次附加到路由路径上,最终造成前缀重复显示。

解决办法

方案1:在include_router阶段设置前缀

将前缀配置从APIRouter实例初始化时移到app.include_router的参数中,避免重复叠加:

import uvicorn
from fastapi import FastAPI, APIRouter, Request
from fastapi_utils.cbv import cbv

router = APIRouter(tags=["sample"])

@cbv(router)
class Server:
    @router.get("/hello")
    async def connect(self, request: Request):
        return "world"

app = FastAPI()
app.include_router(router=router, prefix="/sample")
uvicorn.run(app, host="0.0.0.0", port=22222)

此时正确的访问路径为/sample/hello,不会出现前缀重复。

方案2:使用FastAPI原生类视图实现

放弃依赖fastapi_utils,用FastAPI原生方式实现类路由,从根源避免兼容性问题:

import uvicorn
from fastapi import FastAPI, APIRouter, Request

class ServerRouter(APIRouter):
    def __init__(self):
        super().__init__(prefix="/sample", tags=["sample"])
        self.add_api_route("/hello", self.connect, methods=["GET"])
    
    async def connect(self, request: Request):
        return "world"

app = FastAPI()
app.include_router(ServerRouter())
uvicorn.run(app, host="0.0.0.0", port=22222)

原生实现稳定性更强,不会出现前缀重复问题。

内容的提问来源于stack exchange,提问作者user1476860

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 01:52:33