Serverless Application With API Gateway, AWS Lambda, and DynamoDB Using SAM.
By: Souvik Paul
Tags: Api Gateway, Sam Cli, Nodejs, AWS Lambda, Dynamodb

The objective of this article is to create two lambda functions. Out of which, one function will write datas to the DynamoDB table and the other function will read datas from the DynamoDB table. Moreover, both the functions will be invoked by API Gateway calls.

Basically, in this project, we are following the Single Responsibility Principle(SRP), as both the lambdas have unique and only one responsibility.

It is important to note that this project will be created in our local machine and then it will be deployed into AWS Cloud.

Before jumping into procedures to build the application, let’s understand the basics of the AWS services that we are going to use.

Amazon API Gateway

AWS API gateway is a fully managed service that makes it easy for developers to create, publish, maintain, monitor and secure APIs. API acts as a front door for the application to access data, business logic or functionality from the backend services. It handles all the task involved in accepting and processing up of hundreds or thousands of concurrent API calls, including traffic management, authorization, access control, monitoring and API management.

For this project, there will also be one front door to our application with two resources. One resource will invoke one lambda and the other resource will invoke another lambda.

AWS Lambda

AWS lambda lets the user to run code without provisioning or managing servers and the user needs to pay for how much they use. The user can also scale it up and down according to their needs.

Amazon DynamoDB

Amazon DynamoDB is a fully managed proprietary NoSQL database service that supports key-value and document data structures. It allows us to create database tables that can store and retrieve any amount of data. It also relieves the customers from the burden of operating and scaling a distributed database.

AWS Serverless Application Model (AWS SAM)

The AWS Serverless Application Model (AWS SAM) is an open-source framework that we can use to build serverless applications on AWS.

A serverless application is a combination of Lambda functions, event sources, and other resources that work together to perform tasks. Note that a serverless application is more than just a Lambda function — it can include additional resources such as APIs, databases, and event source mappings.

We can use AWS SAM to define our serverless applications. AWS SAM consists of the following components:

AWS SAM template specification- We use this specification to define our serverless application. It provides us with a simple and clean syntax to describe the functions, APIs, permissions, configurations, and events that make up a serverless application. We use an AWS SAM template file to operate on a single, deployable, versioned entity that’s our serverless application.

We use this specification to define our serverless application. It provides us with a simple and clean syntax to describe the functions, APIs, permissions, configurations, and events that make up a serverless application. We use an AWS SAM template file to operate on a single, deployable, versioned entity that’s our serverless application. AWS SAM command line interface (AWS SAM CLI)- We use this tool to build serverless applications that are defined by AWS SAM templates. The CLI provides commands that enable us to verify that AWS SAM template files are written according to the specification, invoke Lambda functions locally, step-through debug Lambda functions, package and deploy serverless applications to the AWS Cloud, and so on.

SAM is an extension of CloudFormation that allows us to build CloudFormation templates using a set of commands in a less verbose format. We provide SAM with a simplified instructions for our environment and the SAM transforms that information into a fully detailed CloudFormation template.

In a SAM template, the transform directive tells the CloudFormation that this is a SAM template and it should be transformed.

API Gateway event message structure

Let’s see an example of API Gateway event message structure, as we need to parse it using the lambda function to extract the event body.

The event object contains information from the invoker(API Gateway). The invoker passes this information as a JSON-formatted string to the runtime, and the runtime converts it to an object.

So, from this event message, we need to parse the body which is '{"id":"1","name":"ram"}' .

Prerequisites

You should have an AWS account. You should have a basic knowledge of Node.js. Postman or CURL should be installed in your system. AWS CLI and SAM CLI should also be installed in your system.

Now, it’s time to start building our serverless application.

The entire project is also available in my GitHub repository -

Step 1: We’ll create a directory named myproj in our local system, which will be dedicated for this project. In this directory, we’ll create two more directories and one file named template.yaml. Below diagram will explain the directory structure.

Step 2: In the template.yaml file, we’ll specify all the resources that we are going to deploy. For this project, this file will look like the following.

In this template.yaml file, we’ve defined two lambda functions and one DynamoDB table explicitly. We’ve also defined one API gateway resource with two different paths for both lambdas implicitly.

Step 3: Now, we’ll write the code for the lambda function which will perform write operation on the DynamoDB table in write.js file.

We’ll write the code for the lambda function which will perform read operation on the DynamoDB table in read.js file.

In the above lambda codes, we are using Asynchronous functions, which means one statement in the code will not wait for the previous statement to complete. We’ve used await and promise() while putting the items to the DynamoDB table so that the subsequent statements will get executed only after this.

The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise . If the Promise is rejected, the await expression throws the rejected value.

Step 4: Since, we are importing aws-sdk module in both the lambda functions, we need to add a package.json file in both the folders which contain the code for lambda function.

In the folder functionWrite, the package.json will have the following content.

{

"name": "myproj",

"version": "1.0.0",

"description": "",

"main": "write.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

},

"author": "",

"license": "ISC",

"dependencies": {

"aws-sdk": "^2.783.0"

}

}

And in the folder functionRead, the package.json will have the following content.

{

"name": "myproj",

"version": "1.0.0",

"description": "",

"main": "read.js",

"scripts": {

"test": "echo \"Error: no test specified\" && exit 1"

},

"author": "",

"license": "ISC",

"dependencies": {

"aws-sdk": "^2.783.0"

}

}

Step 5: Now, we’ll open the terminal and navigate to myproj directory and run the command sam validate to check whether the template.yaml file is a valid SAM template or not. In our case, it’s a valid SAM template.

Then, well run another command sam build which will start building the application by installing the required node modules and other files.

After this, we’ll run sam deploy --guided which will guide us to enter the name of our stack, region etc. to create a samconfig.toml file. Let’s say, we’ve entered our stack name as myStack and region as ap-south-1. After this, SAM will deploy all the resources into the AWS cloud, which we can verify by opening the CloudFormation console.

Step 6: In the CloudFormation console, we’ll open the API Gateway resource. From there, we can find the invoke URL, which will look like the following,

https://12345abcde.execute-api.ap-south-1.amazonaws.com/Prod

Step 7: Now, it’s time to test whether our application is working properly or not.

We’ll open the terminal and enter the following command.

curl -X POST -d '{"id":"1","name":"ram"}' https://12345abcde.execute-api.ap-south-1.amazonaws.com/Prod/writedb

The above command will give output as {message : Item entered successfully} .

Now, we’ll run the command to read data from the DynamoDB table.

curl -X POST -d '{"id":"1"}' https://12345abcde.execute-api.ap-south-1.amazonaws.com/Prod/readdb

This command will give output as {message : {id:{S:"1"}, name:{S:"ram"}}} .

Step 8: So, our application is working perfectly. Now, let’s delete the application stack from the AWS Cloud. For that, we’ll use the command -

aws cloudformation delete-stack --stack-name myStack

Summary

In this article, we have learnt the basics of AWS Lambda, Amazon API Gateway, DynamoDB, SAM CLI and the structure of API Gateway event message. Finally, we have created a serverless application in our local system and deployed it into the AWS Cloud using SAM CLI.

References: