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

AWS SAM模板中为Step Functions集成添加Integration Response映射模板的方法

针对你的需求,有两种可行的实现方式,不需要完全重写现有模板:

方案1:内嵌OpenAPI定义(更简洁,推荐)

SAM的AWS::Serverless::Api资源支持通过DefinitionBody字段内嵌OpenAPI规范,你可以直接在OpenAPI里定义接口的集成响应模板,同时保留原有的Auth、用量计划等SAM原生配置,不需要单独创建整条Method资源链。

修改后的模板示例:

Transform: AWS::Serverless-2016-10-31
Description: My SAM Template
Resources: 

  MyAPIGateway:
    Type: AWS::Serverless::Api
    Properties:
      Name: my-api
      StageName: beta
      Auth:
        ApiKeyRequired: true 
        UsagePlan: 
          CreateUsagePlan: PER_API
          UsagePlanName: my-usage-plan
          Quota:
            Limit: 1000
            Period: DAY
          Throttle:
            BurstLimit: 1000
            RateLimit: 1000
      # 新增OpenAPI定义
      DefinitionBody:
        openapi: 3.0.1
        info:
          title: my-api
          version: '1.0'
        paths:
          /myApiMethod:
            post:
              security:
                - ApiKeyAuth: []
              x-amazon-apigateway-integration:
                type: aws
                uri: !Sub arn:aws:apigateway:${AWS::Region}:states:action/StartExecution
                httpMethod: POST
                credentials: !GetAtt ApiGatewayStepFunctionRole.Arn
                requestTemplates:
                  application/json: !Sub |
                    {
                      "stateMachineArn": "${MyStateMachine}",
                      "input": "$util.escapeJavaScript($input.body)"
                    }
                responses:
                  default:
                    statusCode: 200
                    # 你需要的响应映射模板
                    responseTemplates:
                      application/json: |
                        #set($executionArn = $input.json('$.executionArn'))
                        #set($arnTokens = $executionArn.split(':'))
                        #set($lastIndex = $arnTokens.size() - 1)
                        #set($executionId = $arnTokens[$lastIndex].replace('"',''))
                        {
                          "execution_id" : "$executionId",
                          "request_id" : "$context.requestId",
                          "request_start_time" : "$context.requestTimeEpoch"
                        }
              responses:
                '200':
                  description: 成功响应
        components:
          securitySchemes:
            ApiKeyAuth:
              type: apiKey
              name: x-api-key
              in: header
      
  MyStateMachine:
    Type: AWS::Serverless::StateMachine
    Properties:
      Name: my-state-machine
      DefinitionUri: statemachines/my-state-machine.asl.json
      # 移除原来的Api事件配置,避免重复生成接口

  # 新增API网关调用Step Function的权限角色
  ApiGatewayStepFunctionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: apigateway.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: StepFunctionExecutionPolicy
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action: states:StartExecution
                Resource: !Ref MyStateMachine
方案2:手动创建CloudFormation API资源链

如果不想用OpenAPI,也可以手动创建AWS::ApiGateway::Method、Integration、IntegrationResponses资源,和你已有的SAM生成的API网关关联:

  1. 首先删除MyStateMachine下的Api事件配置,避免SAM自动生成重复的接口
  2. 手动添加以下资源即可:
# 手动定义接口方法
MyApiMethod:
  Type: AWS::ApiGateway::Method
  Properties:
    RestApiId: !Ref MyAPIGateway
    ResourceId: !GetAtt MyAPIGateway.RootResourceId
    HttpMethod: POST
    AuthorizationType: NONE
    ApiKeyRequired: true
    Integration:
      Type: AWS
      Uri: !Sub arn:aws:apigateway:${AWS::Region}:states:action/StartExecution
      HttpMethod: POST
      Credentials: !GetAtt ApiGatewayStepFunctionRole.Arn
      RequestTemplates:
        application/json: !Sub |
          {
            "stateMachineArn": "${MyStateMachine}",
            "input": "$util.escapeJavaScript($input.body)"
          }
      IntegrationResponses:
        - StatusCode: 200
          ResponseTemplates:
            application/json: |
              #set($executionArn = $input.json('$.executionArn'))
              #set($arnTokens = $executionArn.split(':'))
              #set($lastIndex = $arnTokens.size() - 1)
              #set($executionId = $arnTokens[$lastIndex].replace('"',''))
              {
                "execution_id" : "$executionId",
                "request_id" : "$context.requestId",
                "request_start_time" : "$context.requestTimeEpoch"
              }
    MethodResponses:
      - StatusCode: 200

两种方案都可以实现需求,OpenAPI方案更简洁、代码量更少,是目前SAM生态下推荐的实现方式,并非只有OpenAPI这一种方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 06:45:05