Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门。本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
使用同步快速状态机创建 API Gateway REST APIAmazon CDK
本教API Gateway 您展示如何使用Amazon Cloud Development Kit (Amazon CDK). 本教程将使用该StepFunctionsRestApi
构造将状态机连接到 API Gateway。该StepFunctionsRestApi
构造将设置默认的输入/输出映射和 API Gateway REST API,具有所需的权限和 HTTP “ANY” 方法。Amazon CDK 是一个基础架构即代码 (IAC) 框架,可以让您用完整的编程语言定义 Amazon 基础设施使。您使用 CDK 支持的语言之一编写应用程序,包含一个Amazon CloudFormation或多个堆栈Amazon。我们将使用它来定义一个 API Gateway REST 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 GU I 安装指定的 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
-
在import
里面添加以下内容stepfunctions-rest-api.go
。
"github.com/aws/aws-cdk-go/awscdk/awsapigateway"
"github.com/aws/aws-cdk-go/awscdk/awsstepfunctions"
步骤 2:使用创建Amazon CDK与同步 Express 状态机后端集成
首先,我们将介绍定义同步快速状态机和 API Gateway REST API 的各个代码,然后解释如何将它们组合到您的Amazon CDK应用程序中。然后,您将看到如何合成和部署这些资源。
我们将在此处显示的状态机将是一个带有状态的简单Pass
状态机。
创建快速状态机
这是定义带有状态的简单状态机的Amazon CDK代码。Pass
- TypeScript
-
const machineDefinition = new sfn.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 stepfunctions.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,
})
你可以在这个简短的片段中看到:
使用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/core';
import * as stepfunctions from '@awscdk/aws-stepfunctions';
import * as apigateway from '@aws-cdk/aws-apigateway';
export 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 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('@awscdk/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 stepfunctions.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 core as cdk
from aws_cdk import aws_stepfunctions as sfn
from aws_cdk import aws_apigateway as apigw
class StepfunctionsRestApiStack(cdk.Stack):
def __init__(self, scope: cdk.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#
-
更新 scr/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 policy。正在创建的策略看起来应如下所示:
步骤 3:测试 API Gateway
在使用同步快速状态机作为后端集成创建 API Gateway REST API 后,您可以测试 API Gateway。
使用 API Gateway 控制台测试已部署的 API Gateway
-
打开 Amazon API Gateway 控制台并登录。
-
选择名为的 REST APIStepFunctionsRestApi
。
-
在资源窗格中,选择要测试的方法。在本教程中,以下所ANY
示。
-
在 Method Execution (方法执行) 窗格中的 Client (客户端) 框中,选择 TEST。
-
从 “方法” 下拉菜单中选择 POST。在请求正文中键入值。控制台会以默认 application/json 形式将这些值包括在方法请求中。出于本教程的目的,在请求正文中键入以下内容:
{
"key": "Hello"
}
-
选择 Test (测试)。此时将显示以下信息:
响应正文的输出应如下所示:
"Hello"
尝试使用不同的方法和无效输入的 API Gateway 来查看错误输出。您可能需要更改状态机以查找特定的密钥,并在测试期间提供错误的密钥以使状态机执行失败,并在响应正文输出中生成错误消息。
使用 cURL 测试已部署的 API
-
打开终端窗口。
-
复制以下 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
。