Amazon API Gateway: Build CRUD Microservice with REST API and Lambda

In this article, we are going to develop Hands-on Lab: Build CRUD Microservice with REST API and Lambda.

Hands-on Lab: Build CRUD Microservice with REST API and Lambda

In this hands-on lab, we basically create a Serverless API that creates, reads, updates, and deletes items. We will handle incoming request from REST API of API Gateway into Lambda function and return back to response synchronously.

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

Hands-on Lab: Build CRUD Microservice with REST API and Lambda

When you invoke your REST API, API Gateway routes the request to your Lambda function. The Lambda function interacts with database, and returns a response to API Gateway. API Gateway then returns a response to you. We will start with creating Lambda function, API Gateway and DynamoDB table with using AWS Management Console.

Hands-on Lab: Build CRUD Microservice with REST API and Lambda

Create a Lambda function

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

Goto Console — Lambda — Choose Create function. — For Function name, enter productFunction — Choose Create function.

The example function returns a 200 response to clients, and the text Hello from Lambda. The default Lambda function code should look similar to the following: And please add logging line of code:

exports.handler = async (event) => {
console.log(“event:”, JSON.stringify(event, undefined, 2));
// TODO handle events coming from api gateway http api and perform crudconst response = {
statusCode: 200,
body: JSON.stringify(‘Hello from Lambda!’),
};
return response;
};

We will develop this lambda function after understanding incoming event json format. But before that we should create HTTP API.

Create REST API

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 APIsGET /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

Now we can test our api with sending request:

Send Request:
https://xxxxx.execute-api.us-east-2.amazonaws.com/product
Response:
"Hello from Lambda!"

Understanding How REST API Trigger Lambda with Event Json Object

We are going to Understand How REST API Trigger Lambda with Event Json Object and after that we will develop our lambda function with incoming event to perform crud operations. Lets check incoming event to lambda function:

2022-05-24T11:08:59.918Z 93a04945-289a-434f-93a3-41b397bf5906 INFO event: {
"version": "2.0",
"routeKey": "GET /product",
"rawPath": "/product",...
},
"isBase64Encoded": false
}

So this is the event json object that trigger to lambda function from REST API gateway. If you check this, we can find important parameters like; event.httpMethod, event.pathParameters, queryStringParameters.

Develop Lambda Function for Incoming REST API Event JSON Object

We are going to Develop Lambda Function for Incoming REST API Event JSON Object to perform crud operations. Lets get started. Develop our logic:

exports.handler = async (event) => {
console.log(“event:”, JSON.stringify(event, undefined, 2));
let body;

try {
switch (event.httpMethod) {
case “GET”:
if(event.queryStringParameters != null) {
body = `Processing Get Product Id with “${event.pathParameters.id}” and Category with “${event.queryStringParameters.category}” `; // GET product/1234?category=Phone
}
else if (event.pathParameters != null) {
body = `Processing Get Product Id with “${event.pathParameters.id}”`; // GET product/1234
} else {
body = `Processing Get All Products`; // GET product
}
break;
case “POST”:
let payload = JSON.parse(event.body);
body = `Processing Post Product with “${payload}”`; // POST /product
break;
case “DELETE”:
if(event.pathParameters != null) {
body = `Processing Delete Product Id with “${event.pathParameters.id}”`; // DELETE product/1234
}
break;
default:
throw new Error(`Unsupported route: “${event.httpMethod}”`);
}
console.log(body);
return {
statusCode: 200,
body: JSON.stringify({
message: `Successfully finished operation: “${event.httpMethod}”`,
body: body
})
};
} catch (e) {
console.error(e);
return {
statusCode: 400,
body: JSON.stringify({
message: “Failed to perform operation.”,
errorMsg: e.message
})
};
}
};

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.

E2E Test HTTP 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