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

AWS Lambda通过Function URL正常调用,但API Gateway路径解析异常求助

问题解决:FastAPI + Mangum 部署 API Gateway 路径解析错误

核心问题根源

API Gateway 转发请求到 Lambda 时,会将**完整的请求路径(包含阶段名和资源路径)**传递给 Lambda,而 FastAPI 默认基于根路径匹配路由,若未正确配置路径前缀剥离,就会出现路由不匹配的情况。Function URL 正常是因为它直接映射 Lambda,没有额外的路径前缀。

分步解决方案

1. 修正 API Gateway 路由配置

首先确保 API Gateway 用通配符路由转发所有请求到 Lambda:

  • 进入 API Gateway → 目标 API → Develop → Routes
  • 创建一个 ANY 方法的路由,路径设为 /{proxy+}
  • 将该路由集成到你的 Lambda 函数(确保集成请求的路径设置为 {proxy},传递完整路径)

2. 正确配置路径前缀(二选一即可)

根据你的 API Gateway URL 前缀(比如 https://xxx.execute-api.region.amazonaws.com/default_stage/myFunction 中的 /default_stage/myFunction),选择以下一种配置:

方案A:设置 FastAPI 的 root_path

from fastapi import FastAPI
from mangum import Mangum

# 填入 API Gateway 的完整路径前缀
app = FastAPI(root_path="/default_stage/myFunction")
handler = Mangum(app, lifespan="off")

@app.get("/")
def root():
    return "匹配 /default_stage/myFunction/"

@app.get("/k")
def k():
    return "匹配 /default_stage/myFunction/k"

方案B:设置 Mangum 的 api_gateway_base_path

from fastapi import FastAPI
from mangum import Mangum

app = FastAPI()
# 填入 API Gateway 的完整路径前缀
handler = Mangum(app, lifespan="off", api_gateway_base_path="/default_stage/myFunction")

@app.get("/")
def root():
    return "匹配 /default_stage/myFunction/"

@app.get("/k")
def k():
    return "匹配 /default_stage/myFunction/k"

⚠️ 注意:不要同时设置 root_path 和 api_gateway_base_path,否则会导致路径被重复剥离,引发错误。

3. 清理冗余路由

删除代码中所有带前缀的路由(比如 /myFunction、/default_stage/myFunction 这类),只保留基于根路径的路由即可。配置前缀后,FastAPI 会自动将请求路径的前缀剥离,再匹配你的路由规则。

4. 验证与排错

  • 测试 API Gateway URL:
    • 访问 https://xxx.execute-api.region.amazonaws.com/default_stage/myFunction/ 应返回 root 函数结果
    • 访问 https://xxx.execute-api.region.amazonaws.com/default_stage/myFunction/k 应返回 k 函数结果
  • 若仍有问题,查看 Lambda 日志中的 event 对象,确认 path 字段的值是否符合预期,再调整前缀配置。

内容的提问来源于stack exchange,提问作者starriet 차주녕

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 01:54:56