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

FastAPI中如何同时使用Depends与Path?

解决方案

方法一:将依赖整合到Path参数中

修改event_id的定义,把依赖函数通过Path的dependency参数传入,这样既能保留Swagger所需的示例、描述和范围限制,又能正常触发依赖:

event_id = Annotated[
    int,
    fastapi.Path(
        example=123,
        description="Lore",
        gt=5,
        le=100,
        dependency=fastapi.Depends(dependency_function)
    ),
]

方法二:显式声明依赖(备用)

如果不想调整Path的定义,也可以在路由函数中额外声明依赖,但这种方式会产生冗余代码,不推荐:

# 保持原event_id定义不变
@router.get('/events/{base_id}')
def asd(base_id: common_input_types.event_id, _=Depends(dependency_function)) -> None:
    do_something()

原因说明

原写法中,当Path参数的Annotated同时包含Depends和Path时,FastAPI会优先处理Path的元数据配置,不会自动触发Depends中的依赖函数。通过将依赖传入Path的dependency参数,FastAPI会在验证Path参数的同时执行依赖函数,实现两者功能的同时生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 03:24:54