【问题标题】:Integrating API gateway with SAM template to have custom name and stage将 API 网关与 SAM 模板集成以具有自定义名称和阶段
【发布时间】:2026-01-14 23:05:02
【问题描述】:

我正在尝试为通过 SAM 模板创建的 API 网关提供客户名称。 并且还限制在部署时只创建一个阶段。

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: An AWS Serverless Specification template describing your function.
Resources:
  ApiGatewayApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Development
      Cors: "'*'"
  GetAllUser:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: loadeo_get_all_user
      CodeUri: code/
      Handler: get_all_user.lambda_handler
      Timeout: 5
      Runtime: python3.8
      Role: lambda_execution
      MemorySize: 128
      Events:
        GetAllUser:
          Type: Api
          Properties:
            Path: /get-all-user
            Method: get
            RestApiId:
              Ref: ApiGatewayApi

一切正常,但

  1. 它正在使用堆栈名称创建 API(我想提供自定义名称)
  2. 除了“开发”之外,它还在部署时添加了“阶段”。

我怎样才能实现这两种情况?

【问题讨论】:

    标签: amazon-web-services aws-lambda aws-api-gateway serverless aws-sam


    【解决方案1】:

    要为您的ApiGatewayApi 指定Name,您必须使用Name 属性:

    API Gateway RestApi 资源的名称

    因此您的ApiGatewayApi 将是:

      ApiGatewayApi:
        Type: AWS::Serverless::Api
        Properties:
          StageName: Development
          Name: MyApiName
          Cors: "'*'"
    

    我不确定我是否理解第二个问题,因此目前无法评论。

    正如here 解释的那样,您可以添加以下内容来修复Stage 问题:

    Globals:
      Api:
        OpenApiVersion: 3.0.1
    

    【讨论】:

    • 现在已经编辑了问题,希望我现在清楚
    • 它起作用了:D。不知道您如何找到所有这些解决方案,尤其是针对这一解决方案。再次感谢您
    • @sumanthshetty 您的问题包含问题重现所需的所有详细信息。所以我运行代码,确认它确实是一个问题,找到了一个可能的解决方案,尝试检查它是否有效。因为它对我有用,所以我将它添加到答案中:-)
    • 像你一样学习一种找到解决方案的方法:D