diff --git a/apigw-sfn-crud-terraform/Postman.json b/apigw-sfn-crud-terraform/Postman.json new file mode 100644 index 000000000..e862351cb --- /dev/null +++ b/apigw-sfn-crud-terraform/Postman.json @@ -0,0 +1,139 @@ +{ + "info": { + "_postman_id": "1045b2bc-58ae-4a8d-9f0b-35d5cb44e266", + "name": "Random", + "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", + "_exporter_id": "8276188" + }, + "variable": [ + { + "key": "endpoint", + "value": "", + "type": "string" + }, + { + "key": "id", + "value": "", + "type": "string" + } + ], + "item": [ + { + "name": "DDB Read All", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{endpoint}}", + "host": [ + "{{endpoint}}" + ] + } + }, + "response": [] + }, + { + "name": "DDB Read One", + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{endpoint}}/{{id}}", + "host": [ + "{{endpoint}}" + ], + "path": [ + "{{id}}" + ] + } + }, + "response": [] + }, + { + "name": "DDB Delete", + "request": { + "method": "DELETE", + "header": [], + "url": { + "raw": "{{endpoint}}/{{id}}", + "host": [ + "{{endpoint}}" + ], + "path": [ + "{{id}}" + ] + } + }, + "response": [] + }, + { + "name": "DDB Create", + "request": { + "method": "POST", + "header": [], + "body": { + "mode": "raw", + "raw": "{\n \"make\":\"MINI\",\n \"model\": \"Countryman\",\n \"year\": 2015,\n \"trim\": \"JCW All Four\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{endpoint}}", + "host": [ + "{{endpoint}}" + ] + } + }, + "response": [] + }, + { + "name": "DDB Update", + "request": { + "method": "PUT", + "header": [], + "body": { + "mode": "raw", + "raw": "{\"message\":\"my message again from postman\"}", + "options": { + "raw": { + "language": "json" + } + } + }, + "url": { + "raw": "{{endpoint}}/{{id}}", + "host": [ + "{{endpoint}}" + ], + "path": [ + "{{id}}" + ] + } + }, + "response": [] + } + ], + "event": [ + { + "listen": "prerequest", + "script": { + "type": "text/javascript", + "exec": [ + "" + ] + } + }, + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "" + ] + } + } + ] +} diff --git a/apigw-sfn-crud-terraform/README.md b/apigw-sfn-crud-terraform/README.md new file mode 100644 index 000000000..21bd4cbfc --- /dev/null +++ b/apigw-sfn-crud-terraform/README.md @@ -0,0 +1,71 @@ +# Amazon API Gateway, AWS Step Functions, to Amazon DynamoDB CRUD API + +This stack creates a fully functioning CRUD API powered by Amazon API Gateway direct integration to AWS Step Functions and backed by Amazon DynamoDB. + +*CRUD = Create, Read, Update, Delete* + +Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/apigw-sfn-crud-terraform + +Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example. + +## Requirements + +* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources. +* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured +* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) +* [Terraform](https://learn.hashicorp.com/tutorials/terraform/install-cli?in=terraform/aws-get-started) installed + +## Deployment Instructions + +1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository: + ``` + git clone https://github.com/aws-samples/serverless-patterns + ``` +2. Change directory to the pattern directory: + ``` + cd apigw-sfn-crud-terraform + ``` +3. From the command line, initialize terraform to download and install the providers defined in the configuration: + ``` + terraform init + ``` +4. From the command line, apply the configuration in the main.tf file: + ``` + terraform apply + ``` +5. During the prompts: + * Enter yes +6. Note the outputs from the deployment process. These contain the resource names and/or URLs which are used for testing. + +## How it works + +Amazon API Gateway creates a direct integration with AWS Step Functions utilizing a synchronous call. The Step Functions state machine evaluates the path and method to choose the proper action. The action steps can be modified to meet your needs. + +## Testing + +Once your application is up and running, you can verify the CRUD operations in two ways: +- Make a curl request directly to the endpoint shown in the Terraform output +- Use Postman by importing the provided collection file (make sure to update the endpoint URLs to match your deployed environment) + +Both methods will allow you to test and interact with your API endpoints. + +## Cleanup +1. Change directory to the pattern directory: + ``` + cd apigw-sfn-crud-terraform + ``` +2. Delete all created resources by terraform + ```bash + terraform destroy + ``` +3. During the prompts: + * Enter yes +4. Confirm all created resources has been deleted + ```bash + terraform show + ``` +---- +Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: MIT-0 + diff --git a/apigw-sfn-crud-terraform/apigw-sfn-crud-terraform.json b/apigw-sfn-crud-terraform/apigw-sfn-crud-terraform.json new file mode 100644 index 000000000..9c6ac609c --- /dev/null +++ b/apigw-sfn-crud-terraform/apigw-sfn-crud-terraform.json @@ -0,0 +1,92 @@ +{ + "title": "Amazon API Gateway, AWS Step Functions, to Amazon DynamoDB CRUD API", + "description": "Create a CRUD API with AWS Step Functions.", + "language": "", + "level": "200", + "framework": "Terraform", + "introBox": { + "headline": "Create a CRUD API with AWS Step Functions.", + "text": [ + "This stack creates a fully functioning CRUD API powered by Amazon API Gateway direct integration to AWS Step Functions and backed by Amazon DynamoDB." + ] + }, + "gitHub": { + "template": { + "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-sfn-crud-terraform", + "templateURL": "serverless-patterns/apigw-sfn-crud-terraform", + "projectFolder": "apigw-sfn-crud-terraform", + "templateFile": "main.tf" + } + }, + "resources": { + "bullets": [ + { + "text": "Synchronous Express Workflows for AWS Step Functions", + "link": "https://aws.amazon.com/blogs/compute/new-synchronous-express-workflows-for-aws-step-functions" + }, + { + "text": "API Gateway VTL", + "link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/rest-api-data-transformations.html" + }, + { + "text": "Simple CRUD with API Gateway & DynamboDB", + "link": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-ddb-openapi-crud" + } + ] + }, + "deploy": { + "text": [ + "terraform init", + "terraform apply" + ] + }, + "testing": { + "text": [ + "See the GitHub repo for detailed testing instructions." + ] + }, + "cleanup": { + "text": [ + "terraform destroy" + ] + }, + "authors": [ + { + "name": "Oriol Matavacas", + "image": "https://togithub.s3.eu-west-1.amazonaws.com/Oriol.jpg", + "bio": "Oriol Matavacas is a Senior Solutions Architect at AWS based in Barcelona. Oriol primarily supports customers on the journey to the Cloud. He enjoys building new solutions with scalability, availability and easy to maintain by using serverless.", + "linkedin": "oriol-matavacas-rodriguez-b165868a", + "twitter": "" + } + ], + "patternArch": { + "icon1": { + "x": 20, + "y": 50, + "service": "apigw", + "label": "API Gateway REST API" + }, + "icon2": { + "x": 50, + "y": 50, + "service": "sfn", + "label": "AWS Step Functions" + }, + "icon3": { + "x": 80, + "y": 50, + "service": "dynamodb", + "label": "Amazon DynamoDB" + }, + "line1": { + "from": "icon1", + "to": "icon2", + "label": "" + }, + "line2": { + "from": "icon2", + "to": "icon3", + "label": "" + } + } +} diff --git a/apigw-sfn-crud-terraform/crud-asl.json b/apigw-sfn-crud-terraform/crud-asl.json new file mode 100644 index 000000000..44ad325cc --- /dev/null +++ b/apigw-sfn-crud-terraform/crud-asl.json @@ -0,0 +1,105 @@ +{ + "Comment" : "Definition of the checks and DynamoDB state machine workflow operations", + "StartAt" : "Does ID exist?", + "States" : { + "Does ID exist?" : { + "Type" : "Choice", + "Choices" : [ { + "Variable" : "$.pathParam", + "IsPresent" : true, + "Next" : "Check HTTP Method with ID" + } ], + "Default" : "Check HTTP Method" + }, + "Check HTTP Method" : { + "Type" : "Choice", + "Choices" : [ { + "Variable" : "$.httpMethod", + "StringMatches" : "POST", + "Next" : "Create Item" + } ], + "Default" : "Scan" + }, + "Scan" : { + "Type" : "Task", + "Parameters" : { + "TableName" : "${DDBTable}" + }, + "Resource" : "arn:aws:states:::aws-sdk:dynamodb:scan", + "End" : true + }, + "Create Item" : { + "Type" : "Task", + "Resource" : "arn:aws:states:::dynamodb:putItem", + "Parameters" : { + "TableName" : "${DDBTable}", + "Item" : { + "id" : { + "S.$" : "States.UUID()" + }, + "data" : { + "M.$" : "$.data" + } + } + }, + "ResultPath" : null, + "End" : true + }, + "Check HTTP Method with ID" : { + "Type" : "Choice", + "Choices" : [ { + "Variable" : "$.httpMethod", + "StringMatches" : "PUT", + "Next" : "Update Item" + }, { + "Variable" : "$.httpMethod", + "StringMatches" : "DELETE", + "Next" : "DynamoDB DeleteItem" + } ], + "Default" : "Get Item" + }, + "Get Item" : { + "Type" : "Task", + "Resource" : "arn:aws:states:::dynamodb:getItem", + "Parameters" : { + "TableName" : "${DDBTable}", + "Key" : { + "id" : { + "S.$" : "$.pathParam" + } + } + }, + "End" : true + }, + "Update Item" : { + "Type" : "Task", + "Resource" : "arn:aws:states:::dynamodb:putItem", + "Parameters" : { + "TableName" : "${DDBTable}", + "Item" : { + "id" : { + "S.$" : "$.pathParam" + }, + "data" : { + "M.$" : "$.data" + } + } + }, + "ResultPath" : null, + "End" : true + }, + "DynamoDB DeleteItem" : { + "Type" : "Task", + "Resource" : "arn:aws:states:::dynamodb:deleteItem", + "Parameters" : { + "TableName" : "${DDBTable}", + "Key" : { + "id" : { + "S.$" : "$.pathParam" + } + } + }, + "End" : true + } + } +} diff --git a/apigw-sfn-crud-terraform/example-pattern.json b/apigw-sfn-crud-terraform/example-pattern.json new file mode 100644 index 000000000..0b92eadc3 --- /dev/null +++ b/apigw-sfn-crud-terraform/example-pattern.json @@ -0,0 +1,63 @@ +{ + "title": "Amazon API Gateway, AWS Step Functions, to Amazon DynamoDB CRUD API", + "description": "Create a CRUD API with AWS Step Functions.", + "language": "", + "level": "200", + "framework": "Terraform", + "introBox": { + "headline": "Create a CRUD API with AWS Step Functions.", + "text": [ + "This stack creates a fully functioning CRUD API powered by Amazon API Gateway direct integration to AWS Step Functions and backed by Amazon DynamoDB." + ] + }, + "gitHub": { + "template": { + "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-sfn-crud-terraform", + "templateURL": "serverless-patterns/apigw-sfn-crud-terraform", + "projectFolder": "apigw-sfn-crud-terraform", + "templateFile": "main.tf" + } + }, + "resources": { + "bullets": [ + { + "text": "Synchronous Express Workflows for AWS Step Functions", + "link": "https://aws.amazon.com/blogs/compute/new-synchronous-express-workflows-for-aws-step-functions" + }, + { + "text": "API Gateway VTL", + "link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/rest-api-data-transformations.html" + }, + { + "text": "Simple CRUD with API Gateway & DynamboDB", + "link": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-ddb-openapi-crud" + } + ] + }, + "deploy": { + "text": [ + "terraform init", + "terraform apply" + ] + }, + "testing": { + "text": [ + "See the GitHub repo for detailed testing instructions." + ] + }, + "cleanup": { + "text": [ + "terraform destroy" + ] + }, + "authors": [ + { + "name": "Oriol Matavacas", + "image": "https://togithub.s3.eu-west-1.amazonaws.com/Oriol.jpg", + "bio": "Oriol Matavacas is a Senior Solutions Architect at AWS based in Barcelona. Oriol primarily supports customers on the journey to the Cloud. He enjoys building new solutions with scalability, availability and easy to maintain by using serverless.", + "linkedin": "oriol-matavacas-rodriguez-b165868a", + "twitter": "" + } + ] +} + diff --git a/apigw-sfn-crud-terraform/main.tf b/apigw-sfn-crud-terraform/main.tf new file mode 100644 index 000000000..3484eab69 --- /dev/null +++ b/apigw-sfn-crud-terraform/main.tf @@ -0,0 +1,401 @@ +terraform { + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 5.0" + } + } + + required_version = ">= 0.14.9" +} + +# Fetching current Account ID and AWS region +data "aws_caller_identity" "current" {} +data "aws_region" "current" {} + +################################################################# +# API Gateway REST +################################################################# +# Creating the API Gateway +resource "aws_api_gateway_rest_api" "API_SF_CRUD-tf_API" { + name = "API_SF_CRUD-tf_API" +} + +# Creating a CloudWatch Log Group for API Gateway access logs +resource "aws_cloudwatch_log_group" "API_SF_CRUD-tf_APILogGroup" { + name = "/aws/vendedlogs/api/API_SF_CRUD-tf_APILogGroup" +} + +# Creating necessary IAM roles and policies for API Gateway +resource "aws_iam_role" "API_SF_CRUD-tf_APIRole" { + name = "API_SF_CRUD-tf_APIRole" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Principal = { + Service = "apigateway.amazonaws.com" + } + Action = "sts:AssumeRole" + } + ] + }) +} + +resource "aws_iam_role_policy" "API_SF_CRUD-tf_APIPolicy" { + name = "API_SF_CRUD-tf_APIPolicy" + role = aws_iam_role.API_SF_CRUD-tf_APIRole.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "states:StartExecution" + ] + Resource = "${aws_sfn_state_machine.API_SF_CRUD-tf_CF.arn}" + }, + { + Effect = "Allow" + Action = [ + "states:StartSyncExecution" + ] + Resource = "${aws_sfn_state_machine.API_SF_CRUD-tf_CF.arn}" + }, + ] + }) +} + +resource "aws_iam_role_policy_attachment" "API_SF_CRUD-tf_APIPolicyAttachment1" { + role = aws_iam_role.API_SF_CRUD-tf_APIRole.name + policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonAPIGatewayPushToCloudWatchLogs" + depends_on = [ aws_iam_role.API_SF_CRUD-tf_APIRole ] +} + +resource "aws_iam_role_policy_attachment" "API_SF_CRUD-tf_APIPolicyAttachment2" { + role = aws_iam_role.API_SF_CRUD-tf_APIRole.name + policy_arn = "arn:aws:iam::aws:policy/AWSXrayWriteOnlyAccess" + depends_on = [ aws_iam_role.API_SF_CRUD-tf_APIRole ] +} + +# Root resource is build-in, but child (/{id}) resource is needed +resource "aws_api_gateway_resource" "API_SF_CRUD-tf_APIRes_Child" { + parent_id = aws_api_gateway_rest_api.API_SF_CRUD-tf_API.root_resource_id + path_part = "{id}" + rest_api_id = aws_api_gateway_rest_api.API_SF_CRUD-tf_API.id +} + +# Creating a ANY method for both resources +resource "aws_api_gateway_method" "API_SF_CRUD-tf_API_method" { + resource_id = aws_api_gateway_rest_api.API_SF_CRUD-tf_API.root_resource_id + rest_api_id = aws_api_gateway_rest_api.API_SF_CRUD-tf_API.id + http_method = "ANY" + authorization = "NONE" + depends_on = [aws_api_gateway_rest_api.API_SF_CRUD-tf_API] +} + +resource "aws_api_gateway_method" "API_SF_CRUD-tf_API_method_child" { + resource_id = aws_api_gateway_resource.API_SF_CRUD-tf_APIRes_Child.id + rest_api_id = aws_api_gateway_rest_api.API_SF_CRUD-tf_API.id + http_method = "ANY" + authorization = "NONE" + request_parameters = { + "method.request.path.id" = true + } + depends_on = [aws_api_gateway_resource.API_SF_CRUD-tf_APIRes_Child] +} + +# Creating API Gateway behaviour for root / resource ANY method +resource "aws_api_gateway_integration" "API_SF_CRUD-tf_APIInt" { + rest_api_id = aws_api_gateway_rest_api.API_SF_CRUD-tf_API.id + resource_id = aws_api_gateway_rest_api.API_SF_CRUD-tf_API.root_resource_id + http_method = aws_api_gateway_method.API_SF_CRUD-tf_API_method.http_method + integration_http_method = "POST" + type = "AWS" + uri = "arn:aws:apigateway:${data.aws_region.current.name}:states:action/StartExecution" + credentials = aws_iam_role.API_SF_CRUD-tf_APIRole.arn + passthrough_behavior = "NEVER" + request_templates = { + "application/json" = <