

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# AWS CDK を使用して Step Functions で Express ワークフローを作成する
<a name="tutorial-step-functions-rest-api-integration-cdk"></a>

このチュートリアルでは、Infrastructure as Code (IAC) フレームワークを使用して、同期エクスプレスステートマシンをバックエンド統合として API Gateway REST API AWS Cloud Development Kit (AWS CDK) を作成する方法について説明します。

このチュートリアルでは、`StepFunctionsRestApi` コンストラクトを使用してステートマシンを API Gateway に接続します。`StepFunctionsRestApi` コンストラクトは、必要なアクセス許可と HTTP「ANY」メソッドを使用して、デフォルトの入出力マッピングと API Gateway REST API を設定します。

 AWS CDK は Infrastructure as Code (IAC) フレームワークで、プログラミング言語を使用して AWS インフラストラクチャを定義します。CDK でサポートされている言語のいずれかでアプリケーションを定義し、コードを CloudFormation テンプレートに合成してから、インフラストラクチャを AWS アカウントにデプロイします。

 CloudFormation を使用して、同期 Express ステートマシンと統合された API Gateway REST API をバックエンドとして定義し、 を使用して実行 AWS マネジメントコンソール を開始します。

このチュートリアルを開始する前に、[「 AWS CDK - 前提条件の開始方法](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html#getting_started_prerequisites)」の説明に従って AWS CDK 開発環境を設定し、以下を発行 AWS CDK して をインストールします。

```
npm install -g aws-cdk
```

## ステップ 1: AWS CDK プロジェクトをセットアップする
<a name="step-functions-rest-api-integration-cdk-step-1"></a>

まず、新しい AWS 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
```

プロジェクトが初期化されたら、プロジェクトの仮想環境をアクティブ化し、 AWS 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\$1 ]

```
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` としてください。 AWS CDK アプリケーションテンプレートは、ディレクトリ名を使用し、ソースファイルとクラスの名前を生成します。別の名前を使用する場合は、アプリはこのチュートリアルと一致しません。

次に、 AWS 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\$1 ]

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

また、Visual Studio NuGet GUIを使用して、示されたパッケージをインストールすることもできます。**ツール** > **NuGet パッケージマネージャー** > **ソリューションの NuGet パッケージの管理**の手順で可能です。

------

モジュールをインストールしたら、次のパッケージをインポートして AWS 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\$1 ]

```
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: AWS CDK を使用して、同期 Express ステートマシンバックエンド統合で API Gateway REST API を作成する
<a name="step-functions-rest-api-integration-cdk-step-2"></a>

最初に、同期高速ステートマシンと API Gateway REST API を定義する個々のコードを紹介し、それらを AWS CDK アプリケーションにまとめる方法を説明します。次に、これらのリソースを合成してデプロイする方法を見ていきます。

**注記**  
ここで紹介するステートマシンは、`Pass` ステートのシンプルなステートマシンです。

### 高速ステートマシンを作成するには
<a name="step-functions-rest-api-integration-cdk-create-state-machine"></a>

これは、 `Pass` 状態を持つ単純なステートマシンを定義する AWS 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\$1 ]

```
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`。
+ マシンの定義がステートマシン定義として使用されます。
+ `StepFunctionsRestApi` は同期高速ステートマシンのみを許可するため、ステートマシンタイプは `EXPRESS` に設定されています。

### `StepFunctionsRestApi` コンストラクトを使用して API Gateway REST API を作成するには
<a name="step-functions-rest-api-integration-cdk-create-rest-api"></a>

`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\$1 ]

```
var api = new StepFunctionsRestApi(this, "StepFunctionsRestApi", new StepFunctionsRestApiProps
{
    StateMachine = stateMachine
});
```

------
#### [ Go ]

```
awsapigateway.NewStepFunctionsRestApi(stack, jsii.String("StepFunctionsRestApi"), &awsapigateway.StepFunctionsRestApiProps
{
    StateMachine = stateMachine,
})
```

------

### AWS CDK アプリを構築してデプロイするには
<a name="step-functions-rest-api-integration-cdk-app"></a>

作成した AWS 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\$1 ]

以下のように `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("account-id"),
    //  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` アプリケーションのメインディレクトリで発行します。はアプリケーション AWS CDK を実行し、そこから CloudFormation テンプレートを合成して、テンプレートを表示します。

Amazon API Gateway と AWS Step Functions ステートマシンを実際に AWS アカウントにデプロイするには、 を発行します`cdk deploy`。が生成 AWS CDK した IAM ポリシーを承認するように求められます。

## ステップ 3: API Gateway をテストする
<a name="step-functions-rest-api-integration-cdk-step-3"></a>

同期高速ステートマシンをバックエンド統合として使用して API Gateway REST API を作成したら、API Gateway をテストできます。

### API Gateway を使用してデプロイされた API Gateway をテストするには
<a name="to-test-the-deployed-api-gateway-using-console"></a>

1. [Amazon API Gateway コンソール](https://console.aws.amazon.com/apigateway/)を開き、サインインします。

1. `StepFunctionsRestApi` という名前の REST API を選択します。

1. **[リソース]** ペインで、`ANY` メソッドを選択します。

1. **[テスト]** タブを選択します。タブを表示するには、右矢印ボタンを選択する必要がある場合があります。

1. [**Method (メソッド)**] で [**POST**] を選択します。

1. **[リクエスト本文]** には、以下のリクエストパラメータをコピーします。

   ```
   {
       "key": "Hello"
   }
   ```

1. **[テスト]** を選択します。次の情報が表示されます。
   + [**リクエスト**]: メソッド用に呼び出されたリソースのパスです。
   + [**ステータス**]: 応答の HTTP ステータスコードです。
   + [**レイテンシー**]: 発信者からリクエストを受信してから応答を返すまでの時間です。
   + **[レスポンス本文]** は HTTP レスポンスの本文です。
   + **[レスポンスヘッダー]** は HTTP レスポンスのヘッダーです。
   + **[ログ]** にはシミュレートされた Amazon CloudWatch Logs エントリが表示され、このメソッドが API Gateway コンソール外で呼び出された場合は書き込まれています。
**注記**  
CloudWatch Logs エントリはシミュレートされていますが、メソッドの呼び出しの結果は現実のものです。

**[レスポンス本文]** の出力は、次のようになります。

```
"Hello"
```

**ヒント**  
さまざまなメソッドと無効な入力で API Gateway を試して、エラー出力を確認してください。特定のキーを検索するステートマシンを変更し、テスト中に間違ったキーを指定してステートマシンの実行を失敗させ、**[レスポンス本文]** の出力にエラーメッセージを生成させる場合があります。

### cURL を使用して デプロイされた API をテストするには
<a name="to-test-the-deployed-api-gateway-using-curl"></a>

1. ターミナルウィンドウを開きます。

1. 次の 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: クリーンアップする
<a name="step-functions-rest-api-integration-cdk-step-4"></a>

API Gateway の試行が完了したら、AWS CDK を使用してステートマシンと API Gateway の両方をティアダウンできます。アプリケーションのメインディレクトリで `cdk destroy` を発行します。