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

含两个必填路径参数的SAM API Gateway配置构建失败但本地正常

排查SAM Build时API Gateway路径参数RequestParameters类型错误问题

核心问题原因

sam build严格遵循CloudFormation官方Schema校验,而sam local start-api对格式要求更宽松,所以会出现本地运行正常但构建报错的情况。常见的错误点集中在RequestParameters的键名格式和值的类型上。

正确配置示例

场景1:在SAM Function的Events中直接定义API

SAMPLEFUNCTION:
  Type: AWS::Serverless::Function
  Properties:
    CodeUri: src/
    Handler: app.lambda_handler
    Runtime: python3.11
    Events:
      SampleAdminApi:
        Type: Api
        Properties:
          Path: /admin/test/{organization_id}/sample/{section_id}
          Method: GET
          # 注意键名格式和值的类型
          RequestParameters:
            method.request.path.organization_id: true
            method.request.path.section_id: true
          # 如果使用自定义API Gateway,需指定RestApiId
          RestApiId: !Ref AdminApiGateway

场景2:单独定义AWS::ApiGateway::Method资源

SampleApiResource:
  Type: AWS::ApiGateway::Resource
  Properties:
    RestApiId: !Ref AdminApiGateway
    ParentId: !GetAtt AdminApiGateway.RootResourceId
    PathPart: admin

# 逐层创建嵌套资源(省略中间层级的resource定义)
SampleSectionResource:
  Type: AWS::ApiGateway::Resource
  Properties:
    RestApiId: !Ref AdminApiGateway
    ParentId: !Ref SampleSampleResource
    PathPart: "{section_id}"

SampleMethod:
  Type: AWS::ApiGateway::Method
  Properties:
    RestApiId: !Ref AdminApiGateway
    ResourceId: !Ref SampleSectionResource
    HttpMethod: GET
    AuthorizationType: AWS_IAM
    # 必填参数配置
    RequestParameters:
      method.request.path.organization_id: true
      method.request.path.section_id: true
    Integration:
      Type: AWS_PROXY
      IntegrationHttpMethod: POST
      Uri: !Sub arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${SAMPLEFUNCTION.Arn}/invocations

关键排查点

  • 键名必须严格匹配规范:必须使用method.request.path.{参数名}格式,不能简化为path.organization_id或其他写法,SAM local可能兼容,但sam build会判定类型无效。
  • 值必须是布尔类型:直接写true(小写,无引号),不要写成字符串"true",CloudFormation要求该属性为布尔值,字符串类型会触发类型错误。
  • 层级缩进要准确:确保RequestParameters直接位于Api或Method的Properties下,和Path、Method同级,嵌套错误也会导致校验失败。
  • 检查Integration层的映射(如果需要):如果要将路径参数传递到Lambda,在Integration.RequestParameters中需添加映射规则(如场景2示例),但这不是构建报错的直接原因,只是功能完整性检查。

验证方法

修改配置后,先执行sam validate命令提前校验模板格式,这个命令会模拟sam build的校验逻辑,能快速定位类型错误,比直接执行sam build更高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 17:42:29