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

设置routePrefix非空时Azure Function集成FastAPI端点失效求助

解决FastAPI部署为Azure Function时routePrefix导致的404问题

问题原因

当你在host.json中设置routePrefix: "api"后,Azure Functions会自动给所有请求路径添加/api前缀。例如请求http://localhost:7071/api/someEndpoint到达你的Function时,请求路径变为/api/someEndpoint,但你的FastAPI应用中定义的路由是/someEndpoint,两者不匹配,因此FastAPI返回"Not Found"。

解决方案

方案一:给FastAPI设置root_path

直接在FastAPI实例初始化时指定root_path,让FastAPI自动识别并处理前缀:

# backend/main.py
from fastapi import FastAPI

# 对应Azure Functions的routePrefix值
app = FastAPI(root_path="/api")

@app.get("/someEndpoint")
async def some_endpoint():
    return {"message": "Hello World"}

如果需要兼容本地开发和部署环境,可以通过环境变量动态获取前缀:

# backend/main.py
import os
from fastapi import FastAPI

# Azure Functions会自动设置FUNCTIONS_ROUTE_PREFIX环境变量,值为你设置的routePrefix(带斜杠,比如"/api")
root_path = os.getenv("FUNCTIONS_ROUTE_PREFIX", "")
app = FastAPI(root_path=root_path)

方案二:在Function中修改请求路径

如果不想修改FastAPI代码,可以在Function的处理函数中手动剥离前缀后再转发:

# __init__.py
import logging
import azure.functions as func
from backend.main import app

async def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
    try:
        # 移除/api前缀(根据你的routePrefix调整长度)
        if req.url.path.startswith("/api"):
            req._url = req.url._replace(path=req.url.path[4:])
        return await func.AsgiMiddleware(app).handle_async(req, context)
    except Exception as e:
        return func.HttpResponse(str(e), status_code=200)

注意:此方法依赖Azure Functions HttpRequest的内部实现,版本更新可能导致失效,优先推荐方案一。

方案三:调整Function路由配置

保持routePrefix为空,在function.json的路由规则中添加前缀:

  1. 修改host.json:
{
  "extensions": {
    "http": {
        "routePrefix": ""
    }
  }
}
  1. 修改function.json的route字段:
"route": "api/{*route}"

这样请求http://localhost:7071/api/someEndpoint会被Function捕获,转发给FastAPI时路径自动变为/someEndpoint,与FastAPI的路由匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:02:42