Select your cookie preferences

We use cookies and similar tools to enhance your experience, provide our services, deliver relevant advertising, and make improvements. Approved third parties also use these tools to help us deliver advertising and provide certain site features.

API Gateway to Step Functions

Created with SnapAPI Gateway HTTP APIStep FunctionsStartSyncExecution

Create an API Gateway HTTP APIs endpoint that starts a Step Functions syncronous Express Workflow

This pattern explains how to deploy an API Gateway HTTP API that synchronously invokes a Step FunctionsExpress Workflow and returns the output state of the workflow in the HTTP request response body. The CDK application also creates a log group that Step Functions writes execution data into.

using System.Collections.Generic;
using Amazon.CDK;
using Amazon.CDK.AWS.APIGateway;
using Amazon.CDK.AWS.Apigatewayv2;
using Amazon.CDK.AWS.DynamoDB;
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.AWS.Lambda;
using Amazon.CDK.AWS.Logs;
using Amazon.CDK.AWS.SAM;
using Amazon.CDK.AWS.StepFunctions;
using AssetOptions = Amazon.CDK.AWS.S3.Assets.AssetOptions;
using Constructs;

namespace Cdk
{
    public class CdkStack : Stack
    {
        internal CdkStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            var startState = new Pass(this, "StartState");

            var logGroup = new LogGroup(this, "HttpExpressWorkflowLogGroup");

            var stepFunction = new StateMachine(this, "HttpExpressWorkflow", new StateMachineProps()
            {
                StateMachineName = "HttpExpressWorkflowExample",
                StateMachineType = StateMachineType.EXPRESS,
                Definition = startState,
                Logs = new LogOptions()
                {
                    Destination = logGroup,
                    Level = LogLevel.ALL
                },
                TracingEnabled = true
            });

            var apiGatewayRole = new Role(this, "ApiGatewayRole", new RoleProps()
            {
                AssumedBy = new ServicePrincipal("apigateway.amazonaws.com")
            });

            apiGatewayRole.AddToPolicy(new PolicyStatement(new PolicyStatementProps()
            {
                Effect = Effect.ALLOW,
                Sid = "AllowStepFunctionExecution",
                Actions = new string[1] {"states:StartSyncExecution"},
                Resources = new string[1] {stepFunction.StateMachineArn}
            }));

            var httpApi = new CfnHttpApi(this, "HttpApi", new CfnHttpApiProps()
            {
                StageName = "Main",
            });

            var integration = new CfnIntegration(this, "StepFunctionIntegration", new CfnIntegrationProps()
            {
                ApiId = httpApi.Ref,
                IntegrationType = "AWS_PROXY",
                IntegrationSubtype = "StepFunctions-StartSyncExecution",
                CredentialsArn = apiGatewayRole.RoleArn,
                RequestParameters = new Dictionary(2)
                {
                    { "Input", "$request.body"},
                    { "StateMachineArn", stepFunction.StateMachineArn}
                },
                PayloadFormatVersion = "1.0",
                ConnectionType = "INTERNET"
            });

            var route = new CfnRoute(this, "StepFunctionRoute", new CfnRouteProps()
            {
                ApiId = httpApi.Ref,
                RouteKey = "POST /execute",
                Target = $"integrations/{integration.Ref}"
            });
        }
    }
}

< Back to all patterns


GitHub icon Visit the GitHub repo for this pattern.

Download

git clone https://github.com/aws-samples/serverless-patterns/ cd serverless-patterns/apigw-sfn-cdk

Deploy

cdk deploy


Testing

Run the following command to send an HTTP `POST` request to the HTTP APIs endpoint. Note, you must edit the {HelloWorldApi} placeholder with the URL of the deployed HTTP APIs endpoint. This is provided in the stack outputs:
curl --location --request POST '{HelloWorldApi}' --header 'Content-Type: application/json' --data-raw '{ "IsHelloWorldExample": "Yes" }'

Cleanup

1. Delete the stack: cdk destroy.
2. Confirm the stack has been deleted: aws cloudformation list-stacks --query "StackSummaries[?contains(StackName,'STACK_NAME')].StackStatus"

James Eastham

Presented by James Eastham

I am a Cloud Infrastructure Architect with AWS Professional Services.