Amazon API Gateway: Build CRUD Microservice with HTTP API and Lambda
In this article, we are going to develop Hands-on Lab: Build CRUD Microservice with HTTP 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 HTTP 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 HTTP API and Lambda
When you invoke your HTTP 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.
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 HTTP API
API Gateway also supports REST APIs and WebSocket APIs, but an HTTP API is the best choice for this exercise. HTTP APIs have lower latency and lower cost than REST APIs.
Goto API Gateway — create an HTTP API — For Integrations, choose Add integration — Choose Lambda — productFunction — API Name — product-api.
Configure HTTP API Route
Routes are a way to send incoming API requests to backend resources. Routes consist of two parts: an HTTP method and a resource path, for example, GET /products. Find our product api methods:
CRUD Product APIsGET /product
GET /product/{id}
POST /product
DELETE /product/{id}
After that Attach your integration to routes and then choose Create API Gateway HTTP API. Now all routes show that an AWS Lambda integration is attached. Now we can test our api with sending request:
Send Request:
https://xxxxx.execute-api.us-east-2.amazonaws.com/productResponse:
"Hello from Lambda!"
Understanding How HTTP API Trigger Lambda with Event Json Object
We are going to Understand How HTTP 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:
event: {
“version”: “2.0”,
“routeKey”: “GET /product”,
“rawPath”: “/product”,
“rawQueryString”: “”,
“headers”: {
“accept”: “text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9”,
“accept-encoding”: “gzip, deflate, br”,
“accept-language”: “en-US,en;q=0.9,tr-TR;q=0.8,tr;q=0.7,de;q=0.6,es;q=0.5,ru;q=0.4,th;q=0.3”,
“content-length”: “0”,
“host”: “cg9cloipv8.execute-api.us-east-2.amazonaws.com”,
“sec-ch-ua”: “\” Not A;Brand\”;v=\”99\”, \”Chromium\”;v=\”101\”, \”Google Chrome\”;v=\”101\””,
“sec-ch-ua-mobile”: “?0”,
“sec-ch-ua-platform”: “\”Windows\””,
“sec-fetch-dest”: “document”,
“sec-fetch-mode”: “navigate”,
“sec-fetch-site”: “none”,
“sec-fetch-user”: “?1”,
“upgrade-insecure-requests”: “1”,
“user-agent”: “Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36”,
“x-amzn-trace-id”: “Root=1–628cbccb-48908d9d6f1a89f92884ad24”,
“x-forwarded-for”: “24.133.212.235”,
“x-forwarded-port”: “443”,
“x-forwarded-proto”: “https”
},
“requestContext”: {
“accountId”: “308360398142”,
“apiId”: “cg9cloipv8”,
“domainName”: “cg9cloipv8.execute-api.us-east-2.amazonaws.com”,
“domainPrefix”: “cg9cloipv8”,
“http”: {
“method”: “GET”,
“path”: “/product”,
“protocol”: “HTTP/1.1”,
“sourceIp”: “24.133.212.235”,
“userAgent”: “Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36”
},
“requestId”: “SoJv2i6giYcEMcw=”,
“routeKey”: “GET /product”,
“stage”: “$default”,
“time”: “24/May/2022:11:08:59 +0000”,
“timeEpoch”: 1653390539638
},
“isBase64Encoded”: false
}
So this is the event json object that trigger to lambda function from HTTP API gateway. If you check this, we can find important parameters like;
“routeKey”: “GET /product”,
“rawPath”: “/product”,
According to this parameters we can identify incoming route and http method.
Develop Lambda Function for Incoming HTTP API Event JSON Object
we are going to Develop Lambda Function for Incoming HTTP 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.routeKey) {
case “GET /product”:
body = `Processing Get All Products`; // GET product
break;
case “GET /product/{id}”:
if(event.pathParameters != null) {
body = `Processing Get Product Id with “${event.pathParameters.id}”`; // GET product/1234
}
break;
case “POST /product”:
let payload = JSON.parse(event.body);
body = `Processing Post Product Id with “${payload}”`; // POST /product
break;
case “DELETE /product/{id}”:
if(event.pathParameters != null) {
body = `Processing Delete Product Id with “${event.pathParameters.id}”`; // DELETE product/1234
}
break;
default:
throw new Error(`Unsupported route: “${event.routeKey}”`);
}console.log(body);
return {
statusCode: 200,
body: JSON.stringify({
message: `Successfully finished operation: “${event.routeKey}”`,
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 HTTP 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 HTTP API Event Json Object
we are going to E2E Test HTTP API and Lambda Function with Incoming HTTP 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 HTTP API and Lambda functions and finished Hands-on Lab: Build CRUD Microservice with HTTP 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.