RESTful Microservices with AWS Lambda, API Gateway and DynamoDB

In this article, we are going to build RESTful Microservices with AWS Lambda, API Gateway and DynamoDB.

RESTful Microservices with AWS Lambda, API Gateway and DynamoDB

We will do Hands-on Lab: Building RESTful Microservices with AWS Lambda, API Gateway and DynamoDB. By the end of the article, we will make http call to API Gateway and perform crud logic with AWS Lambda and DynamoDB.

I have just published a new course — AWS Lambda & Serverless — Developer Guide with Hands-on Labs.

RESTful Microservices with AWS Lambda, API Gateway and DynamoDB

When building a microservice, you’re thinking about how a business context can be delivered as a re-usable service for your consumers. For that reason, the implementation should be specific as per individual use cases. But there are common approaches when it comes to develop Restful microservices with using AWS Serverless services.

We are going to create a serverless API that creates, reads, updates, and deletes items from a DynamoDB table. DynamoDB is a fully managed NoSQL database service that provides fast and predictable performance with seamless scalability.

First, we create a DynamoDB table using the DynamoDB console. Then we create a Lambda function using the AWS Lambda console. Next, we create an REST API using the API Gateway console. Lastly, we test your API.

RESTful Microservices with AWS Lambda, API Gateway and DynamoDB

This is the Reference architecture for RESTful microservices.

  • Clients send request our microservices by making HTTP API calls. Ideally, our clients should have a tightly bounded service contract to our API in order to achieve consistent expectations of microservice responsibility.
  • Amazon API Gateway hosts RESTful HTTP requests and responses to customers. In this scenario, API Gateway provides built-in authorization, throttling, security, fault tolerance, request/response mapping, and performance optimizations.
  • AWS Lambda contains the business logic to process incoming API calls and leverage DynamoDB as a persistent storage.
  • Amazon DynamoDB persistently stores microservices data and scales based on demand. Since microservices are often designed to do one thing well, a schema-less NoSQL data store is regularly incorporated.

So when we invoke our Api Gateway API, API Gateway routes the request to your Lambda function. The Lambda function interacts with DynamoDB, and returns a response to API Gateway. API Gateway then returns a response to us.

Create a DynamoDB Table

We are going to Create a DynamoDB table. We use a DynamoDB table to store data for your API. Each item has a unique ID, which we use as the partition key for the table.

To create a DynamoDB table, Open the DynamoDB console at https://console.aws.amazon.com/dynamodb/.

Choose Create table.
For Table name, product

For Primary key,
PK — id.

Choose Create.

Create a Lambda Function

We are going to Create a Lambda function. AWS Lambda is event-driven computing rather than an imperative model. Events-driven computing responds to events when the event source happens, it triggers the lambda function. The event source could be a request to an endpoint which we will go through later using API Gateway.

We create a Lambda function for the backend of your API. This Lambda function creates, reads, updates, and deletes items from DynamoDB. The function uses events from API Gateway to determine how to interact with DynamoDB.

To create a Lambda function; https://console.aws.amazon.com/lambda.

Choose Create function.
For Function name
productFunction

Give Microservice Permission
Under Permissions choose Change default execution role.
Select Create a new role from AWS policy templates.

For Role name
productRole

For Policy templates, choose “Simple microservice permissions”. This policy grants the Lambda function permission to interact with DynamoDB.

Choose Create function.

Develop Lambda Function

Open index.js in the console’s code editor, and replace its contents with the following code.

const AWS = require(“aws-sdk”);
const dynamo = new AWS.DynamoDB.DocumentClient();
exports.handler = async (event, context) => {
let body;
let statusCode = 200;
const headers = {
“Content-Type”: “application/json”
};
try {
switch (event.httpMethod) {
case “DELETE”:
await dynamo
.delete({
TableName: “product”,
Key: {
id: event.pathParameters.id
}
})
.promise();
body = `Deleted product ${event.pathParameters.id}`;
break;
case “GET”:
if (event.pathParameters != null) {
body = await dynamo
.get({
TableName: “product”,
Key: {
id: event.pathParameters.id
}
})
.promise();
} else {
body = await dynamo.scan({ TableName: “product” }).promise();
}
break;
case “POST”:
let requestJSON = JSON.parse(event.body);
await dynamo
.put({
TableName: “product”,
Item: {
id: requestJSON.id,
price: requestJSON.price,
title: requestJSON.title,
description: requestJSON.description,
}
})
.promise();
body = `Added/Updated product ${requestJSON.id}`;
break;
default:
throw new Error(`Unsupported route: “${event.httpMethod}”`);
}
} catch (err) {
statusCode = 400;
body = err.message;
} finally {
body = JSON.stringify(body);
}
return {
statusCode,
body,
headers
};
};

Choose Deploy to update your function.

Basically we handle all incoming request from REST API by looking the route key attributes. After that perform crud operations. To make simple I am not calling any database communications, instead we put body information about the operations.

The handler method is the method that will be executed when the lambda function is invoked. This function takes in two objects, event, and context. the event object contains all of the data sent from the event source and the context object provides several methods that allow you to interact with runtime information specific to that lambda function.

We have Copied the snippet code and paste it to the index.js. By using the event.httpMethod to differentiate the HTTP request, we can perform the create/update/delete and retrieve data from DynamoDB.

Create an API Gateway

API Gateway also supports HTTP APIs and WebSocket APIs, but an REST API is the best choice for this exercise. The REST API provides an REST HTTP endpoint for your Lambda function.

API Gateway routes requests to your Lambda function, and then returns the function’s response to clients. First of all we should design our API resource and methods:

CRUD Product APIs
GET /product
GET /product/{id}
POST /product
DELETE /product/{id}

Now we can create REST API for our example, Create a REST API in API Gateway: Open AWS Console, type API Gateway

Goto API Gateway — create an REST API — productApi — Create Resource — product — Create Methods GET, GetbyId, POST, Delete — Deploy the API

E2E Test REST API and Lambda Function with Incoming REST API Event Json Object

we are going to E2E Test REST API and Lambda Function with Incoming REST API Event Json Object to perform crud operations.
Lets get started. Create request one by one;

GET
https://xxxx.execute-api.us-east-2.amazonaws.com/product
{“message”:”Successfully finished operation: \”GET /product\””,”body”:”Processing Get All Products”}GET by ID
https://xxxx.execute-api.us-east-2.amazonaws.com/product/343
{“message”:”Successfully finished operation: \”GET /product/{id}\””,”body”:”Processing Get Product Id with \”343\””}POST
https://xxxx.execute-api.us-east-2.amazonaws.com/product
payload:
{
“name”:”IPhone”,
“price”:”900"
}
{“message”:”Successfully finished operation: \”POST /product\””,”body”:”Processing Post Product Id with \”[object Object]\””}DELETE
https://xxxxx.execute-api.us-east-2.amazonaws.com/product/343
{“message”:”Successfully finished operation: \”DELETE /product/{id}\””,”body”:”Processing Delete Product Id with \”343\””}

As you can see that we have successfully tested our REST API and Lambda functions and finished Hands-on Lab: Build CRUD Microservice with REST API and Lambda.

Step by Step Design AWS Architectures w/ Course

I have just published a new course — AWS Lambda & Serverless — Developer Guide with Hands-on Labs.

In this course, we will learn almost all the AWS Serverless Services with all aspects. We are going to build serverless applications with using AWS Lambda, Amazon API Gateway, Amazon DynamoDB, Amazon Cognito, Amazon S3, Amazon SNS, Amazon SQS, Amazon EventBridge, AWS Step Functions, DynamoDB and Kinesis Streams. This course will be 100% hands-on, and you will be developing a real-world application with hands-on labs together and step by step.

Source Code

Get the Source Code from Serverless Microservices GitHub — Clone or fork this repository, if you like don’t forget the star. If you find or ask anything you can directly open issue on repository.

--

--

Mehmet Ozkaya
AWS Lambda & Serverless — Developer Guide with Hands-on Labs

Software Architect | Udemy Instructor | AWS Community Builder | Cloud-Native and Serverless Event-driven Microservices https://github.com/mehmetozkaya