DEV Community

codeisgood
codeisgood

Posted on

Create API Gateway with Step Function Integration

Often we need to integrate Lambda with API Gateway which is a very popular pattern, however as we think about asynchronous processing we need to integrate Step Functions (which will have a chain of actions) with API gateway.

Below is a simple terraform example of how to create an API Gateway with Step Function Integration

provider "aws" {
  region = "us-east-1"
}

resource "aws_api_gateway_rest_api" "example_api" {
  name = "example_api"
}

resource "aws_api_gateway_resource" "example_resource" {
  rest_api_id = aws_api_gateway_rest_api.example_api.id
  parent_id   = aws_api_gateway_rest_api.example_api.root_resource_id
  path_part   = "example"
}

resource "aws_api_gateway_method" "example_method" {
  rest_api_id   = aws_api_gateway_rest_api.example_api.id
  resource_id   = aws_api_gateway_resource.example_resource.id
  http_method   = "POST"
  authorization = "NONE"
}

resource "aws_api_gateway_integration" "example_integration_step_function" {
  rest_api_id = aws_api_gateway_rest_api.example_api.id
  resource_id = aws_api_gateway_resource.example_resource.id
  http_method = aws_api_gateway_method.example_method.http_method
  integration_http_method = "POST"
  type = "AWS"

  uri = aws_sfn_state_machine.example_step_function.execution_arn
}

resource "aws_sfn_state_machine" "example_step_function" {
  name = "example_step_function"
  definition = <<EOF
{
  "Comment": "A simple AWS Step Functions state machine",
  "StartAt": "FirstState",
  "States": {
    "FirstState": {
      "Type": "Pass",
      "Result": "Hello, world!",
      "End": true
    }
  }
}
EOF
}

resource "aws_api_gateway_deployment" "example_deployment" {
  depends_on = [
    aws_api_gateway_integration.example_integration_step_function
  ]

  rest_api_id = aws_api_gateway_rest_api.example_api.id
}

Enter fullscreen mode Exit fullscreen mode
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "states:StartExecution"
            ],
            "Resource": [
                "arn:aws:states:<REGION>:<ACCOUNT_ID>:stateMachine:<STATE_MACHINE_NAME>"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": [
                "arn:aws:logs:<REGION>:<ACCOUNT_ID>:log-group:/aws/lambda/<LAMBDA_FUNCTION_NAME>:*"
            ]
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)