使用同步 Express 状态机创建 API Gateway REST API 使用 Amazon CDK - Amazon Step Functions
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用同步 Express 状态机创建 API Gateway REST API 使用 Amazon CDK

本教程将向您展示如何使用 Amazon Cloud Development Kit (Amazon CDK) 通过同步快速状态机创建一个 API Gateway REST API 作为后端集成。本教程将使用 StepFunctionsRestApi 构造将状态机连接到 API Gateway。StepFunctionsRestApi 构造将设置默认的输入/输出映射和 API Gateway REST API,具有所需的权限和 HTTP “ANY” 方法。 Amazon CDK 是一个基础设施即代码 (IAC) 框架,允许您使用成熟的编程语言定义 Amazon 基础架构。您使用 CDK 支持的语言之一编写包含一个或多个堆栈的应用程序,然后将其合成 Amazon CloudFormation 模板并将其部署到您的账户。 Amazon 我们将使用它来定义 API Gateway REST API,该API与同步快速状态机集成为后端,然后使用 Amazon Web Services Management Console 来启动执行。

在开始本教程之前,请按照入门必备条件中所述设置您的 Amazon CDK 开发环境,然后 Amazon CDK 通过发布以下命令进行安装: Amazon CDK

npm install -g aws-cdk

第 1 步:设置您的 Amazon CDK 项目

首先,为您的新 Amazon CDK 应用程序创建一个目录并初始化项目。

TypeScript
mkdir stepfunctions-rest-api cd stepfunctions-rest-api cdk init --language typescript
JavaScript
mkdir stepfunctions-rest-api cd stepfunctions-rest-api cdk init --language javascript
Python
mkdir stepfunctions-rest-api cd stepfunctions-rest-api cdk init --language python

项目初始化后,激活项目的虚拟环境并安装其 Amazon CDK基准依赖关系。

source .venv/bin/activate python -m pip install -r requirements.txt
Java
mkdir stepfunctions-rest-api cd stepfunctions-rest-api cdk init --language java
C#
mkdir stepfunctions-rest-api cd stepfunctions-rest-api cdk init --language csharp
Go
mkdir stepfunctions-rest-api cd stepfunctions-rest-api cdk init --language go
注意

请确保将目录命名为 stepfunctions-rest-api。 Amazon CDK 应用程序模板使用目录的名称为源文件和类生成名称。如果您使用其他名称,则您的应用将与本教程不匹配。

现在为 Amazon Step Functions 和 Amazon API Gateway 安装构造库模块。

TypeScript
npm install @aws-cdk/aws-stepfunctions @aws-cdk/aws-apigateway
JavaScript
npm install @aws-cdk/aws-stepfunctions @aws-cdk/aws-apigateway
Python
python -m pip install aws-cdk.aws-stepfunctions python -m pip install aws-cdk.aws-apigateway
Java

编辑项目的 pom.xml 将以下依赖项添加到现有 <dependencies> 容器。

<dependency> <groupId>software.amazon.awscdk</groupId> <artifactId>stepfunctions</artifactId> <version>${cdk.version}</version> </dependency> <dependency> <groupId>software.amazon.awscdk</groupId> <artifactId>apigateway</artifactId> <version>${cdk.version}</version> </dependency>

Maven 会在下次构建应用程序时自动安装这些依赖关系。要构建,请发出 mvn compile 或使用 Java IDE 的构建命令。

C#
dotnet add src/StepfunctionsRestApi package Amazon.CDK.AWS.Stepfunctions dotnet add src/StepfunctionsRestApi package Amazon.CDK.AWS.APIGateway

您也可以使用 Visual Studio NuGet GUI 安装指定的软件包,该用户界面可通过 “工具” > “NuGet 包管理器” > “管理解决方案 NuGet 包” 获得。

安装模块后,您可以通过导入以下软件包在 Amazon CDK 应用程序中使用它们。

TypeScript
@aws-cdk/aws-stepfunctions @aws-cdk/aws-apigateway
JavaScript
@aws-cdk/aws-stepfunctions @aws-cdk/aws-apigateway
Python
aws_cdk.aws_stepfunctions aws_cdk.aws_apigateway
Java
software.amazon.awscdk.services.apigateway.StepFunctionsRestApi software.amazon.awscdk.services.stepfunctions.Pass software.amazon.awscdk.services.stepfunctions.StateMachine software.amazon.awscdk.services.stepfunctions.StateMachineType
C#
Amazon.CDK.AWS.StepFunctions Amazon.CDK.AWS.APIGateway
Go

将以下内容添加到 stepfunctions-rest-api.go 内的 import

"github.com/aws/aws-cdk-go/awscdk/awsapigateway" "github.com/aws/aws-cdk-go/awscdk/awsstepfunctions"

第 2 步:使用创建具有同步 Express 状态机后端集成的 API Gateway REST API Amazon CDK

首先,我们将介绍定义同步 Express 状态机和 API Gateway REST API 的各个代码,然后解释如何将它们组合到您的 Amazon CDK 应用程序中。然后,您将了解如何合成和部署这些资源。

注意

我们将在此处展示的状态机将是一个带有 Pass 状态的简单状态机。

创建快速状态机

这是定义带有状态的简单Pass状态机的 Amazon CDK 代码。

TypeScript
const machineDefinition = new stepfunctions.Pass(this, 'PassState', { result: {value:"Hello!"}, }) const stateMachine = new stepfunctions.StateMachine(this, 'MyStateMachine', { definition: machineDefinition, stateMachineType: stepfunctions.StateMachineType.EXPRESS, });
JavaScript
const machineDefinition = new sfn.Pass(this, 'PassState', { result: {value:"Hello!"}, }) const stateMachine = new sfn.StateMachine(this, 'MyStateMachine', { definition: machineDefinition, stateMachineType: stepfunctions.StateMachineType.EXPRESS, });
Python
machine_definition = sfn.Pass(self,"PassState", result = sfn.Result("Hello")) state_machine = sfn.StateMachine(self, 'MyStateMachine', definition = machine_definition, state_machine_type = sfn.StateMachineType.EXPRESS)
Java
Pass machineDefinition = Pass.Builder.create(this, "PassState") .result(Result.fromString("Hello")) .build(); StateMachine stateMachine = StateMachine.Builder.create(this, "MyStateMachine") .definition(machineDefinition) .stateMachineType(StateMachineType.EXPRESS) .build();
C#
var machineDefinition = new Pass(this, "PassState", new PassProps { Result = Result.FromString("Hello") }); var stateMachine = new StateMachine(this, "MyStateMachine", new StateMachineProps { Definition = machineDefinition, StateMachineType = StateMachineType.EXPRESS });
Go
var machineDefinition = awsstepfunctions.NewPass(stack, jsii.String("PassState"), &awsstepfunctions.PassProps { Result: awsstepfunctions.NewResult(jsii.String("Hello")), }) var stateMachine = awsstepfunctions.NewStateMachine(stack, jsii.String("StateMachine"), &awsstepfunctions.StateMachineProps { Definition: machineDefinition, StateMachineType: awsstepfunctions.StateMachineType_EXPRESS, })

您可以在这个简短的片段中看到:

  • 名为 PassState 的计算机定义,它是一个 Pass 状态。

  • 状态机的逻辑名称,MyStateMachine

  • 机器定义被用作状态机定义。

  • 状态机类型设置为 EXPRESS,因为 StepFunctionsRestApi 只支持同步快速状态机。

使用 StepFunctionsRestApi 构造创建 API Gateway REST API

我们将使用 StepFunctionsRestApi 构造来创建具有所需权限和默认输入/输出映射的 API Gateway REST API。

TypeScript
const api = new apigateway.StepFunctionsRestApi(this, 'StepFunctionsRestApi', { stateMachine: stateMachine });
JavaScript
const api = new apigateway.StepFunctionsRestApi(this, 'StepFunctionsRestApi', { stateMachine: stateMachine });
Python
api = apigw.StepFunctionsRestApi(self, "StepFunctionsRestApi", state_machine = state_machine)
Java
StepFunctionsRestApi api = StepFunctionsRestApi.Builder.create(this, "StepFunctionsRestApi") .stateMachine(stateMachine) .build();
C#
var api = new StepFunctionsRestApi(this, "StepFunctionsRestApi", new StepFunctionsRestApiProps { StateMachine = stateMachine });
Go
awsapigateway.NewStepFunctionsRestApi(stack, jsii.String("StepFunctionsRestApi"), &awsapigateway.StepFunctionsRestApiProps { StateMachine = stateMachine, })

构建并部署 Amazon CDK 应用程序

在您创建的 Amazon CDK 项目中,编辑包含堆栈定义的文件,使其看起来像下面的代码。您将从上面的部分中了解 Step Functions 状态机和 API Gateway 的定义。

TypeScript

更新 lib/stepfunctions-rest-api-stack.ts 读取如下信息。

import * as cdk from 'aws-cdk-lib'; import * as stepfunctions from 'aws-cdk-lib/aws-stepfunctions' import * as apigateway from 'aws-cdk-lib/aws-apigateway'; export class StepfunctionsRestApiStack extends cdk.Stack { constructor(scope: cdk.App, id: string, props?: cdk.StackProps) { super(scope, id, props); const machineDefinition = new stepfunctions.Pass(this, 'PassState', { result: {value:"Hello!"}, }); const stateMachine = new stepfunctions.StateMachine(this, 'MyStateMachine', { definition: machineDefinition, stateMachineType: stepfunctions.StateMachineType.EXPRESS, }); const api = new apigateway.StepFunctionsRestApi(this, 'StepFunctionsRestApi', { stateMachine: stateMachine });
JavaScript

更新 lib/stepfunctions-rest-api-stack.js 读取如下信息。

const cdk = require('@aws-cdk/core'); const stepfunctions = require('@aws-cdk/aws-stepfunctions'); const apigateway = require('@aws-cdk/aws-apigateway'); class StepfunctionsRestApiStack extends cdk.Stack { constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) { super(scope, id, props); const machineDefinition = new stepfunctions.Pass(this, "PassState", { result: {value:"Hello!"}, }) const stateMachine = new sfn.StateMachine(this, 'MyStateMachine', { definition: machineDefinition, stateMachineType: stepfunctions.StateMachineType.EXPRESS, }); const api = new apigateway.StepFunctionsRestApi(this, 'StepFunctionsRestApi', { stateMachine: stateMachine }); } } module.exports = { StepStack }
Python

更新 stepfunctions_rest_api/stepfunctions_rest_api_stack.py 读取如下信息。

from aws_cdk import App, Stack from constructs import Construct from aws_cdk import aws_stepfunctions as sfn from aws_cdk import aws_apigateway as apigw class StepfunctionsRestApiStack(Stack): def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None: super().__init__(scope, construct_id, **kwargs) machine_definition = sfn.Pass(self,"PassState", result = sfn.Result("Hello")) state_machine = sfn.StateMachine(self, 'MyStateMachine', definition = machine_definition, state_machine_type = sfn.StateMachineType.EXPRESS) api = apigw.StepFunctionsRestApi(self, "StepFunctionsRestApi", state_machine = state_machine)
Java

更新 src/main/java/com.myorg/StepfunctionsRestApiStack.java 读取如下信息。

package com.myorg; import software.amazon.awscdk.core.Construct; import software.amazon.awscdk.core.Stack; import software.amazon.awscdk.core.StackProps; import software.amazon.awscdk.services.stepfunctions.Pass; import software.amazon.awscdk.services.stepfunctions.StateMachine; import software.amazon.awscdk.services.stepfunctions.StateMachineType; import software.amazon.awscdk.services.apigateway.StepFunctionsRestApi; public class StepfunctionsRestApiStack extends Stack { public StepfunctionsRestApiStack(final Construct scope, final String id) { this(scope, id, null); } public StepfunctionsRestApiStack(final Construct scope, final String id, final StackProps props) { super(scope, id, props); Pass machineDefinition = Pass.Builder.create(this, "PassState") .result(Result.fromString("Hello")) .build(); StateMachine stateMachine = StateMachine.Builder.create(this, "MyStateMachine") .definition(machineDefinition) .stateMachineType(StateMachineType.EXPRESS) .build(); StepFunctionsRestApi api = StepFunctionsRestApi.Builder.create(this, "StepFunctionsRestApi") .stateMachine(stateMachine) .build(); } }
C#

更新 src/StepfunctionsRestApi/StepfunctionsRestApiStack.cs 读取如下信息。

using Amazon.CDK; using Amazon.CDK.AWS.StepFunctions; using Amazon.CDK.AWS.APIGateway; namespace StepfunctionsRestApi { public class StepfunctionsRestApiStack : Stack { internal StepfunctionsRestApi(Construct scope, string id, IStackProps props = null) : base(scope, id, props) { var machineDefinition = new Pass(this, "PassState", new PassProps { Result = Result.FromString("Hello") }); var stateMachine = new StateMachine(this, "MyStateMachine", new StateMachineProps { Definition = machineDefinition, StateMachineType = StateMachineType.EXPRESS }); var api = new StepFunctionsRestApi(this, "StepFunctionsRestApi", new StepFunctionsRestApiProps { StateMachine = stateMachine }); } } }
Go

更新 stepfunctions-rest-api.go 读取如下信息。

package main import ( "github.com/aws/aws-cdk-go/awscdk" "github.com/aws/aws-cdk-go/awscdk/awsapigateway" "github.com/aws/aws-cdk-go/awscdk/awsstepfunctions" "github.com/aws/constructs-go/constructs/v3" "github.com/aws/jsii-runtime-go" ) type StepfunctionsRestApiGoStackProps struct { awscdk.StackProps } func NewStepfunctionsRestApiGoStack(scope constructs.Construct, id string, props *StepfunctionsRestApiGoStackProps) awscdk.Stack { var sprops awscdk.StackProps if props != nil { sprops = props.StackProps } stack := awscdk.NewStack(scope, &id, &sprops) // The code that defines your stack goes here var machineDefinition = awsstepfunctions.NewPass(stack, jsii.String("PassState"), &awsstepfunctions.PassProps { Result: awsstepfunctions.NewResult(jsii.String("Hello")), }) var stateMachine = awsstepfunctions.NewStateMachine(stack, jsii.String("StateMachine"), &awsstepfunctions.StateMachineProps{ Definition: machineDefinition, StateMachineType: awsstepfunctions.StateMachineType_EXPRESS, }); awsapigateway.NewStepFunctionsRestApi(stack, jsii.String("StepFunctionsRestApi"), &awsapigateway.StepFunctionsRestApiProps{ StateMachine = stateMachine, }) return stack } func main() { app := awscdk.NewApp(nil) NewStepfunctionsRestApiGoStack(app, "StepfunctionsRestApiGoStack", &StepfunctionsRestApiGoStackProps{ awscdk.StackProps{ Env: env(), }, }) app.Synth(nil) } // env determines the AWS environment (account+region) in which our stack is to // be deployed. For more information see: https://docs.aws.amazon.com/cdk/latest/guide/environments.html func env() *awscdk.Environment { // If unspecified, this stack will be "environment-agnostic". // Account/Region-dependent features and context lookups will not work, but a // single synthesized template can be deployed anywhere. //--------------------------------------------------------------------------- return nil // Uncomment if you know exactly what account and region you want to deploy // the stack to. This is the recommendation for production stacks. //--------------------------------------------------------------------------- // return &awscdk.Environment{ // Account: jsii.String("123456789012"), // Region: jsii.String("us-east-1"), // } // Uncomment to specialize this stack for the AWS Account and Region that are // implied by the current CLI configuration. This is recommended for dev // stacks. //--------------------------------------------------------------------------- // return &awscdk.Environment{ // Account: jsii.String(os.Getenv("CDK_DEFAULT_ACCOUNT")), // Region: jsii.String(os.Getenv("CDK_DEFAULT_REGION")), // } }

保存源文件,然后在应用程序的主目录中发出 cdk synth。 Amazon CDK 运行应用程序并从中合成一个 Amazon CloudFormation 模板,然后显示该模板。

要将 Amazon API Gateway 和 Amazon Step Functions 状态机实际部署到您的 AWS 账户,请执行以下操作cdk deploy。系统将要求您批准 Amazon CDK 已生成的 IAM 策略。正在创建的策略与下面类似:

第 3 步:测试 API Gateway Gateway

使用同步快速状态机创建 API Gateway REST API 作为后端集成后,您可以测试 API Gateway。

使用 API Gateway 控制台测试已部署的 API Gateway

  1. 打开 Amazon API Gateway 控制台并登录。

  2. 选择名为 StepFunctionsRestApi 的 REST API。

  3. 资源窗格中,选择 ANY 方法。

  4. 选择测试选项卡。您可能需要选择右箭头按钮,以显示该选项卡。

  5. 对于方法,选择 POST

  6. 请求正文中,复制以下请求参数。

    { "key": "Hello" }
  7. 选择测试。此时将显示以下信息:

    • 请求是为方法调用的资源路径。

    • 状态是响应的 HTTP 状态代码。

    • 延迟是收到调用方请求和返回响应之间的时间。

    • 响应正文是 HTTP 响应正文。

    • 响应标头是 HTTP 响应标头。

    • 日志显示了在 API Gateway 控制台之外调用此方法时本应写入的模拟 Amazon Lo CloudWatch gs 条目。

      注意

      尽管 CloudWatch 日志条目是模拟的,但方法调用的结果是真实的。

响应正文输出应如下所示:

"Hello"
提示

使用不同的方法和无效的输入来尝试 API Gateway,查看错误输出。您可能希望更改状态机来查找特定的键,并在测试期间提供错误的键,以使状态机执行失败,并在响应正文输出中生成错误消息。

使用 cURL 测试已部署的 API

  1. 打开终端窗口。

  2. 复制以下 cURL 命令将其粘贴到终端窗口中,同时将 <api-id> 替换为您的 API 的 API ID 并将 <region> 替换为部署您的 API 的区域。

    curl -X POST\ 'https://<api-id>.execute-api.<region>.amazonaws.com/prod' \ -d '{"key":"Hello"}' \ -H 'Content-Type: application/json'

响应正文输出应如下所示:

"Hello"
提示

使用不同的方法和无效的输入来尝试 API Gateway,查看错误输出。您可能希望更改状态机来查找特定的键,并在测试期间提供错误的键,以使状态机执行失败,并在响应正文输出中生成错误消息。

第 4 步:清除

当您完成了 API Gateway 测试后,可以使用 AWS CDK 卸载状态机和 API Gateway。在您的应用程序的主目录中发布 cdk destroy