Python 环境下 Azure Function 搭配 FastAPI ASGI 路由前缀配置报错求助
问题原因
你修改function.json的bindings.route为api/{*route}后,Azure Function会正确匹配/api/开头的请求并转发到你的函数入口,但默认的AsgiMiddleware会把完整请求路径(包含/api前缀)直接传给FastAPI做路由匹配,而你FastAPI中注册的接口路径是/user/{user_id},没有对应/api前缀的路由规则,因此FastAPI返回{"detail":"Not Found"}错误。
解决方案
以下两种方案二选一即可:
方案1:给FastAPI配置全局路径前缀(推荐)
初始化FastAPI实例时添加root_path参数,指定前缀为/api,FastAPI会自动在路由匹配时剥离该前缀:
# 改前:app = fastapi.FastAPI() app = fastapi.FastAPI(root_path="/api")
其余代码、function.json的"route": "api/{*route}"配置无需修改,重启后即可正常访问http://localhost:7071/api/user/1。
方案2:复用Azure Function的全局路由前缀配置
修改host.json中的全局路由前缀,由Azure Function层面剥离/api前缀,再将请求传给FastAPI:
- 调整
host.json的extensions.http配置:
"extensions": { "http": { "routePrefix": "api" } }
- 将
function.json的bindings.route改回{*route}
重启函数后,监听地址自动变为http://localhost:7071/api/{*route},请求/api/user/1时Azure Function会自动剥离/api前缀,传给FastAPI的路径为/user/1,可正常匹配现有接口。
内容的提问来源于stack exchange,提问作者Pawel
相关产品推荐
相关产品推荐

