如何使用API​​网关调用AWS步骤函数

时间:2017-03-20 21:42:31

标签: amazon-web-services aws-api-gateway aws-step-functions

如何使用API​​网关POST请求调用AWS步骤函数,以及请求的步骤函数的JSON有效负载?

2 个答案:

答案 0 :(得分:6)

1。创建步骤功能

非常明显。我想如果你正在读这篇文章就知道该怎么做了。

否则,您可以查看以下文档:What is AWS Step Functions?

2。为您的API创建IAM角色

它既可以用于所有步骤功能,也可以只用于此步骤功能。我们将仅讨论第一个案例,如亚马逊教程中所述:Creating an API Using API Gateway

  

创建IAM角色

     
      
  • 登录AWS Identity and Access Management控制台。

  •   
  • 在“角色”页面上,选择“创建新角色”。

  •   
  • 在“设置角色名称”页面上,为“角色名称”键入APIGatewayToStepFunctions,然后选择“下一步”。

  •   
  • 在“选择角色类型”页面的“选择角色类型”下,选择“Amazon API网关”。

  •   
  • 在“附加策略”页面上,选择“下一步”。

  •   
  • 在Review页面上,记下Role ARN,例如:

  •   
  • arn:aws:iam::123456789012:role/APIGatewayToStepFunctions

  •   
  • 选择“创建角色”。
  •   
     

将策略附加到IAM角色

     
      
  • 在“角色”页面上,按名称搜索您的角色(APIGatewayToStepFunctions),然后选择角色。
  •   
  • 在“权限”选项卡上,选择“附加策略”。
  •   
  • 在Attach Policy页面上,搜索AWSStepFunctionsFullAccess,选择策略,然后选择Attach Policy。
  •   

3。设置

3.a如果您没有JSON有效负载

正如Ka Hou Ieong在How can i call AWS Step Functions by API Gateway?中所解释的那样,您可以通过API Gateway Console创建AWS服务集成,如下所示:

  • 集成类型: AWS服务
  • AWS服务:步骤功能
  • HTTP方法: POST
  • 操作类型:使用操作名称
  • 操作: StartExecution
  • 执行角色:开始执行的角色(我们刚创建的角色。只需粘贴它的ARN)
  • 接头:

    X-Amz-Target - > 'AWSStepFunctions.StartExecution'
    内容类型 - > '应用程序/ x-AMZ-JSON-1.0'

  • Body Mapping Templates / Request payload:

    {
        "input": "string" (optional),
        "name": "string" (optional),
        "stateMachineArn": "string"
    }
    

3.b如果您确实要将JSON有效负载作为输入传递

除了身体贴图模板外,一切都与2.a中的相同。你要做的就是把它变成一个字符串。使用$ util.escapeJavascript(),例如这样。它会将您整个请求的正文作为步骤函数的输入

    #set($data = $util.escapeJavaScript($input.json('$')))
    {
        "input": "$data",
        "name": "string" (optional),
        "stateMachineArn": "string" (required)
    }

注释

  • stateMachineArn:如果您不想将stateMachineArn作为API网关请求的一部分传递,您可以在Body Mapping模板中对其进行硬编码(参见AWS API Gateway with Step Function)< / LI>
  • name:省略name属性将使API Gateway在每次执行时为您生成另一个。

现在,这是我的第一个“回答你自己的问题”,所以也许这不是它的完成方式,但我确实花了几个小时试图了解我的映射模板有什么问题。希望这有助于挽救其他人的头发和时间。

答案 1 :(得分:2)

对于那些正在寻求通过OpenApi集成和CloudFormation将 ApiGateway Step Functions状态机直接连接的用户,这是我如何管理的示例使它起作用:

这是我设计的 Visual Workflow (在CloudFormation文件中提供更多详细信息),作为概念证明:

visual workflow

template.yaml

AWSTemplateFormatVersion: 2010-09-09
Transform: 'AWS::Serverless-2016-10-31'
Description: POC Lambda Examples - Step Functions

Parameters:
  CorsOrigin:
    Description: Header Access-Control-Allow-Origin
    Default: "'http://localhost:3000'"
    Type: String
  CorsMethods:
    Description: Header Access-Control-Allow-Headers
    Default: "'*'"
    Type: String
  CorsHeaders:
    Description: Header Access-Control-Allow-Headers
    Default: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key'"
    Type: String
  SwaggerS3File:
    Description: 'S3 "swagger.yaml" file location'
    Default: "./swagger.yaml"
    Type: String

Resources:
  LambdaRoleForRuleExecution:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub ${AWS::StackName}-lambda-role
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action: 'sts:AssumeRole'
            Principal:
              Service: lambda.amazonaws.com
      Policies:
        - PolicyName: WriteCloudWatchLogs
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - 'logs:CreateLogGroup'
                  - 'logs:CreateLogStream'
                  - 'logs:PutLogEvents'
                Resource: 'arn:aws:logs:*:*:*'

  ApiGatewayStepFunctionsRole:
    Type: AWS::IAM::Role
    Properties:
      Path: !Join ["", ["/", !Ref "AWS::StackName", "/"]]
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Sid: AllowApiGatewayServiceToAssumeRole
            Effect: Allow
            Action:
              - 'sts:AssumeRole'
            Principal:
              Service:
                - apigateway.amazonaws.com
      Policies:
        - PolicyName: CallStepFunctions
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - 'states:StartExecution'
                Resource:
                  - !Ref Workflow

  Start:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Sub ${AWS::StackName}-start
      Code: ../dist/src/step-functions
      Handler: step-functions.start
      Role: !GetAtt LambdaRoleForRuleExecution.Arn
      Runtime: nodejs8.10
      Timeout: 1

  Wait3000:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Sub ${AWS::StackName}-wait3000
      Code: ../dist/src/step-functions
      Handler: step-functions.wait3000
      Role: !GetAtt LambdaRoleForRuleExecution.Arn
      Runtime: nodejs8.10
      Timeout: 4

  Wait500:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Sub ${AWS::StackName}-wait500
      Code: ../dist/src/step-functions
      Handler: step-functions.wait500
      Role: !GetAtt LambdaRoleForRuleExecution.Arn
      Runtime: nodejs8.10
      Timeout: 2

  End:
    Type: AWS::Lambda::Function
    Properties:
      FunctionName: !Sub ${AWS::StackName}-end
      Code: ../dist/src/step-functions
      Handler: step-functions.end
      Role: !GetAtt LambdaRoleForRuleExecution.Arn
      Runtime: nodejs8.10
      Timeout: 1

  StateExecutionRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - !Sub states.${AWS::Region}.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Policies:
        - PolicyName: "StatesExecutionPolicy"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: "Allow"
                Action: "lambda:InvokeFunction"
                Resource:
                  - !GetAtt Start.Arn
                  - !GetAtt Wait3000.Arn
                  - !GetAtt Wait500.Arn
                  - !GetAtt End.Arn

  Workflow:
    Type: AWS::StepFunctions::StateMachine
    Properties:
      StateMachineName: !Sub ${AWS::StackName}-state-machine
      RoleArn: !GetAtt StateExecutionRole.Arn
      DefinitionString: !Sub |
        {
          "Comment": "AWS Step Functions Example",
          "StartAt": "Start",
          "Version": "1.0",
          "States": {
            "Start": {
              "Type": "Task",
              "Resource": "${Start.Arn}",
              "Next": "Parallel State"
            },
            "Parallel State": {
              "Type": "Parallel",
              "Next": "End",
              "Branches": [
                {
                  "StartAt": "Wait3000",
                  "States": {
                    "Wait3000": {
                      "Type": "Task",
                      "Resource": "${Wait3000.Arn}",
                      "End": true
                    }
                  }
                },
                {
                  "StartAt": "Wait500",
                  "States": {
                    "Wait500": {
                      "Type": "Task",
                      "Resource": "${Wait500.Arn}",
                      "End": true
                    }
                  }
                }
              ]
            },
            "End": {
              "Type": "Task",
              "Resource": "${End.Arn}",
              "End": true
            }
          }
        }

  RestApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: !Ref Environment
      Name: !Sub ${AWS::StackName}-api
      DefinitionBody:
        'Fn::Transform':
          Name: AWS::Include
          Parameters:
            # s3 location of the swagger file
            Location: !Ref SwaggerS3File

swagger.yaml

openapi: 3.0.0
info:
  version: '1.0'
  title: "pit-jv-lambda-examples"
  description: POC API
  license:
    name: MIT

x-amazon-apigateway-request-validators:
  Validate body:
    validateRequestParameters: false
    validateRequestBody: true
  params:
    validateRequestParameters: true
    validateRequestBody: false
  Validate body, query string parameters, and headers:
    validateRequestParameters: true
    validateRequestBody: true

paths:
  /execute:
    options:
      x-amazon-apigateway-integration:
        type: mock
        requestTemplates:
          application/json: |
            {
              "statusCode" : 200
            }
        responses:
          "default":
            statusCode: "200"
            responseParameters:
              method.response.header.Access-Control-Allow-Headers:
                Fn::Sub: ${CorsHeaders}
              method.response.header.Access-Control-Allow-Methods:
                Fn::Sub: ${CorsMethods}
              method.response.header.Access-Control-Allow-Origin:
                Fn::Sub: ${CorsOrigin}
            responseTemplates:
              application/json: |
                {}
      responses:
        200:
          $ref: '#/components/responses/200Cors'
    post:
      x-amazon-apigateway-integration:
        credentials:
          Fn::GetAtt: [ ApiGatewayStepFunctionsRole, Arn ]
        uri:
          Fn::Sub: arn:aws:apigateway:${AWS::Region}:states:action/StartExecution
        httpMethod: POST
        type: aws
        responses:
          default:
            statusCode: 200
            responseParameters:
              method.response.header.Access-Control-Allow-Headers:
                Fn::Sub: ${CorsHeaders}
              method.response.header.Access-Control-Allow-Origin:
                Fn::Sub: ${CorsOrigin}
          ".*CREATION_FAILED.*":
            statusCode: 403
            responseParameters:
              method.response.header.Access-Control-Allow-Headers:
                Fn::Sub: ${CorsHeaders}
              method.response.header.Access-Control-Allow-Origin:
                Fn::Sub: ${CorsOrigin}
            responseTemplates:
              application/json: $input.path('$.errorMessage')
        requestTemplates:
          application/json:
            Fn::Sub: |-
              {
                "input": "$util.escapeJavaScript($input.json('$'))",
                "name": "$context.requestId",
                "stateMachineArn": "${Workflow}"
              }
      summary: Start workflow
      responses:
        200:
          $ref: '#/components/responses/200Empty'
        403:
          $ref: '#/components/responses/Error'

components:
  schemas:
    Error:
      title: Error
      type: object
      properties:
        code:
          type: string
        message:
          type: string

  responses:
    200Empty:
      description: Default OK response

    200Cors:
      description: Default response for CORS method
      headers:
        Access-Control-Allow-Headers:
          schema:
            type: "string"
        Access-Control-Allow-Methods:
          schema:
            type: "string"
        Access-Control-Allow-Origin:
          schema:
            type: "string"

    Error:
      description: Error Response
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/Error'
      headers:
        Access-Control-Allow-Headers:
          schema:
            type: "string"
        Access-Control-Allow-Origin:
          schema:
            type: "string" 

step-functions.js

exports.start = (event, context, callback) => {
    console.log('start event', event);
    console.log('start context', context);
    callback(undefined, { function: 'start' });
};
exports.wait3000 = (event, context, callback) => {
    console.log('wait3000 event', event);
    console.log('wait3000 context', context);
    setTimeout(() => {
        callback(undefined, { function: 'wait3000' });
    }, 3000);
};
exports.wait500 = (event, context, callback) => {
    console.log('wait500 event', event);
    console.log('wait500 context', context);
    setTimeout(() => {
        callback(undefined, { function: 'wait500' });
    }, 500);
};
exports.end = (event, context, callback) => {
    console.log('end event', event);
    console.log('end context', context);
    callback(undefined, { function: 'end' });
};