Greetings!
I recently started learning AWS serverless. Hence thought to write a little about creating an API in a serverless way. In this post, I am using the manual process, even though it is not the best practice. On a later topic, we will use IaC to build the same.
What is serverless?
Serverless computing means that the cloud provider manages all the necessary infrastructure as the developers can concentrate on the business logic. This does not mean that there are no servers but we developers do not manage them.
What is Lambda
AWS Lambda is a serverless, event-driven, compute service that lets you run code without provisioning or managing servers.
What API Gateway
AWS API Gateway is a fully manages service that makes it easy for developers to create, publish, maintain, monitor, and secure APIs at any scale. It acts as the "front door" for applications to access backend services.
What is DynamoDB
AWS DynamoDB is a fully manages, serverless, key-value NoSQL database designed to run high-performance applications at any scale.
What we will build
We will build a very simple REST endpoint to fetch all data from DynamoDB. I assume that you already have an AWS account.
Let's create the DynamoDB table
Our first step is to create a table in DynamoDB. After that, we will insert a few records manually so that we can fetch those using our REST API.
Go to DynamoDB and select created the table.
Using "add new attributes" we can add our extra fields. After filling click on "create item".
Let's create our Lambda function
Our second step is to create a Lambda function to fetch our notes from the DynamoDB table.
- Create Lambda function
- Update Role to give DynamoDB access
- Create Node.js function to fetch data
- Deploy
Goto Lambda and click on create function.
Here we import managed policy and select DynamoDBFullAccess. Note that this is not the best practice. We should not give additional access but our purpose here is to learn.
After that, go to Code and add node.js code to fetch all items from our table.
const AWS = require('aws-sdk');
const documentClient = new AWS.DynamoDB.DocumentClient({region: 'us-east-1'});
function response(statusCode, data) {
return {
statusCode,
body: JSON.stringify(data),
};
}
exports.handler = async (event) => {
try {
let params = {
TableName: 'notes_table'
};
const data = await documentClient.scan(params).promise();
return response(200, data);
} catch (err) {
console.log("Error", err);
return response(500, "error occured");
}
};
After that click on the "Deploy" button to deploy the Lambda function.
Let's create a REST endpoint using API Gateway
Now it is time to create our REST API using API Gateway.
- Create API
- Create resource
- Create HTTP method
- Connect with Lambda
- Create stage and deploy
Go to API Gateway and choose REST API.
Choose the REST option and New API from the next page.
Comments
Post a Comment