Skip to content

Commit

Permalink
Merge pull request #1434 from nguyendinhthi0705/main
Browse files Browse the repository at this point in the history
Submit a new serverless pattern - API Gateway, Lambda, DynamoDB, Kinesis, Lambda
  • Loading branch information
jbesw authored Jul 7, 2023
2 parents 9fb93ea + 7866f6c commit 8524a2e
Show file tree
Hide file tree
Showing 8 changed files with 235 additions and 0 deletions.
63 changes: 63 additions & 0 deletions apigw-lambda-dynamodb-kinesis-lambda/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# API Gateway, Lambda, DynamoDB, Kinesis, Lambda

This pattern explains how to deploy a SAM application with Amazon API Gateway, AWS Lambda, and Amazon DynamoDB and Stream to Kinesis and finaly trigger a Lambda. When an HTTP POST request is made to the Amazon API Gateway endpoint, the AWS Lambda function is invoked and inserts an item into the Amazon DynamoDB table, then an event will be pushed into Kinesis and trigger a Lambda function

![Concept](img/concept.png)


Learn more about this pattern at Serverless Land Patterns: << Add the https://serverlessland.com/patterns/apigw-lambda-dynamodb-kinesis-lambda

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)
* [AWS Serverless Application Model](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) (AWS SAM) 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
```
1. Change directory to the pattern directory:
```
cd apigw-lambda-dynamodb-kinesis-lambda
```
1. From the command line, use AWS SAM to deploy the AWS resources for the pattern as specified in the template.yml file:
```
sam deploy --guided
```
1. During the prompts:
* Enter a stack name
* Enter the desired AWS Region
* Allow SAM CLI to create IAM roles with the required permissions.

Once you have run `sam deploy --guided` mode once and saved arguments to a configuration file (samconfig.toml), you can use `sam deploy` in future to use these defaults.

1. Note the outputs from the SAM deployment process. These contain the resource names and/or ARNs which are used for testing.

## How it works

Explain how the service interaction works.

## Testing

Provide steps to trigger the integration and show what should be observed if successful.

## Cleanup

1. Delete the stack
```bash
aws cloudformation delete-stack --stack-name STACK_NAME
```
1. Confirm the stack has been deleted
```bash
aws cloudformation list-stacks --query "StackSummaries[?contains(StackName,'STACK_NAME')].StackStatus"
```
----
Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0
66 changes: 66 additions & 0 deletions apigw-lambda-dynamodb-kinesis-lambda/example-pattern.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
{
"title": "API Gateway to Lambda, DynamoDB, Kinesis, Lambda integration",
"description": "Create a api to trigger Lambda, Save to DynamoDB, emit message to Kinesis and trigger a Lambda",
"language": "Python",
"level": "200",
"framework": "SAM",
"introBox": {
"headline": "How it works",
"text": [
"This sample project demonstrates how to use Amazon API Gateway, AWS Lambda, Amazon DynamoDB and Kinesis together. When an HTTP POST request is made to the Amazon API Gateway endpoint, the AWS Lambda function is invoked and inserts an item into the Amazon DynamoDB table, then an event will be pushed into Kinesis and trigger a Lambda function."
]
},
"gitHub": {
"template": {
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/apigw-lambda-dynamodb-kinesis-lambda",
"templateURL": "serverless-patterns/apigw-lambda-dynamodb-kinesis-lambda",
"projectFolder": "apigw-lambda-dynamodb-kinesis-lambda",
"templateFile": "apigw-lambda-dynamodb-kinesis-lambda/sfn_athena_cdk_python_stack.py"
}
},
"resources": {
"bullets": [
{
"text": "API Gateway to trigger Lambda and save to DynamoDB",
"link": "https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-dynamo-db.html"
},
{
"text": "DynamoDB to Kinesis",
"link": "https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/kds.html"
},
{
"text": "Kinesis to Lambda",
"link": "https://docs.aws.amazon.com/lambda/latest/dg/with-kinesis.html"
}
]
},
"deploy": {
"text": [
"sam deploy"
]
},
"testing": {
"text": [
"See the Github repo for detailed testing instructions."
]
},
"cleanup": {
"text": [
"Delete the stack: <code>sam delete</code>"
]
},
"authors": [
{
"name": "Thi Nguyen",
"image": "https://drive.google.com/file/d/188LpzUvUmHt1o7vzbwKw32S-fYabL-qY/view?usp=sharing",
"bio": "Solutions Architect @ AWS",
"linkedin": "https://www.linkedin.com/in/ndthi"
},
{
"name": "Vijay Konade",
"image": "vijay.png",
"bio": "Cloud Support Eng @ AWS",
"linkedin": "https://www.linkedin.com/in/vijay-konade-14427479/"
}
]
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
24 changes: 24 additions & 0 deletions apigw-lambda-dynamodb-kinesis-lambda/src/apiHandler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0

import boto3
import json
dynamodb_client = boto3.resource('dynamodb')

def lambda_handler(event, context):
table = dynamodb_client.Table('Transaction')
print(event)
item = json.loads(event['body'])
print(item)
table.put_item(
Item={
'id': item['id'],
'name': item['name'],
'description': item['description'],
'customer': item['customer']
}
)
return {
'statusCode': 200,
'body': 'Successfully inserted data!'
}
10 changes: 10 additions & 0 deletions apigw-lambda-dynamodb-kinesis-lambda/src/messageHandler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import os
import boto3
from aws_lambda_powertools.utilities.data_classes import KinesisStreamEvent
from aws_lambda_powertools.utilities.typing import LambdaContext

def lambda_handler(event: KinesisStreamEvent, context: LambdaContext):
records = event["Records"]
print(records)
2 changes: 2 additions & 0 deletions apigw-lambda-dynamodb-kinesis-lambda/src/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
aws-xray-sdk
aws_lambda_powertools
70 changes: 70 additions & 0 deletions apigw-lambda-dynamodb-kinesis-lambda/template.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Serverless patterns - Amazon API Gateway to AWS Lambda to Amazon DynamoDB
Parameters:
KinesisStreamName:
Type: String
Default: testDataStream
Description: Enter a name for the Kinesis Data Stream.
Resources:
KinesisStream:
Type: AWS::Kinesis::Stream
Properties:
Name: !Ref KinesisStreamName
ShardCount: 1
LambdaProducerFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: LambdaProducerFunction
Handler: apiHandler.lambda_handler
Runtime: python3.9
CodeUri: src/
Policies:
DynamoDBCrudPolicy:
TableName: !Ref DynamoDBTable
Events:
ApiEvent:
Type: Api
Properties:
Path: /
Method: POST
DynamoDBTable:
Type: AWS::DynamoDB::Table
Properties:
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 5
StreamSpecification:
StreamViewType: NEW_IMAGE
TableName: Transaction
KinesisStreamSpecification:
StreamArn: !GetAtt KinesisStream.Arn

LambdaConsumerFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: LambdaConsumerFunction
Handler: messageHandler.lambda_handler
Runtime: python3.9
CodeUri: src/
Policies:
- KinesisStreamReadPolicy:
StreamName: !Ref KinesisStreamName
Events:
Stream:
Type: Kinesis
Properties:
Stream: !GetAtt KinesisStream.Arn
StartingPosition: LATEST
BatchSize: 100

Outputs:
EndpointUrl:
Description: 'HTTP REST endpoint URL'
Value: !Sub 'https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod'
Binary file added apigw-lambda-dynamodb-kinesis-lambda/vijay.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 8524a2e

Please sign in to comment.