Create a Lambda Function
Now, we will create a lambda function for the backend of our API. The lambda function need to handle the operations for creating, reading, updating and deleting items in DynamoDB.
Steps to create a Lambda Function
- Login your AWS account and go to Lambda Service. Click upon the “Create Function” button to create a lambda function.
- Select “Author from scratch” and write the function name as “blog-api-lambda” and go with the default settings and hit “Create Function” at the end.
- Now in the Code Source, you can see a file “index.mjs”. Rename it as “index.js”.
- Go to the runtime settings and change the runtime to “Node.js 14.x” and save.
- Now replace the contents of index.js with the following code and deploy API.
Node
const dynamoDB = new AWS.DynamoDB.DocumentClient({
region: ‘us-east-1’,
apiVersion: ‘2012-08-10’,
});
exports.handler = async (event, context, callback)=>{
if(event.id === undefined){
if(event.httpMethod === "GET"){ // retrieve all blogs from database
const params = {
TableName: "blog-database"
}
await dynamoDB.scan(params).promise().then((data)=>{
const restructuredData = data.Items.map((newData)=>{
return ({"blogId": newData.blogId, "title": newData.title, "content": newData.content, "author": newData.author});
});
callback(null, restructuredData);
}).catch((err)=>{
callback(err);
})
}
else if(event.httpMethod === "POST"){ // create a blog in the database
const params = {
Item: {
blogId: "blog_"+Math.random(),
title: event.title,
content: event.content,
author: event.author
},
TableName: "blog-database"
}
await dynamoDB.put(params).promise().then((data)=>{
callback(null, data);
}).catch((err)=>{
callback(err);
})
}
else{
callback(null, `Method: ‘${event.httpMethod}’ is not allowed`);
}
}
else{
if(event.httpMethod === "GET"){ // retrieve a particular blog from database
const params = {
Key: {
blogId: event.id
},
TableName: "blog-database"
}
await dynamoDB.get(params).promise().then((data)=>{
const restructuredData = {
"blogId": data.Item.blogId,
"title": data.Item.title,
"content": data.Item.content,
"author": data.Item.author
}
callback(null, restructuredData);
}).catch((err)=>{
callback(err);
})
}
else if(event.httpMethod === "PATCH"){ // updade a particular blog in database
const params = {
Key: {
blogId: event.id
},
UpdateExpression: `set ${event.key} = :value`,
ExpressionAttributeValues: {
":value": event.value
},
TableName: "blog-database",
ReturnValues: "UPDATED_NEW"
};
await dynamoDB.update(params).promise().then((data)=>{
callback(null, data);
}).catch((err)=>{
callback(err);
})
}
else if(event.httpMethod === "DELETE"){ // delete a particular blog from database
const params = {
Key: {
blogId: event.id
},
TableName: "blog-database"
}
await dynamoDB.delete(params).promise().then((data)=>{
callback(null, data);
}).catch((err)=>{
callback(err);
})
}
else{
callback(null, `Method: ‘${event.httpMethod}’ is not allowed`);
}
}
}
- Your Lambda function is ready to be used. But, by default, no service has any permissions. So, we have to provide this lambda function some permissions to read/write access to DynamoDB. So, go to IAM console and go to Roles section. You can see some roles related to lambda function name. Open the role for your lambda function.
- There you can find Attach Policies button inside Add Permissions. Click there and add the “AmazonDynamoDBFullAccess” policy.
- Now, lambda function is ready to access DynamoDB.
Building a Serverless Blog with AWS Lambda and API Gateway
AWS Lambda is a serverless computing service offered by AWS. It enables you to run code in response to events without the need to manage servers. This event-driven service charges you based on actual compute time, making it cost-effective. Lambda supports various programming languages, scales automatically, and seamlessly integrates with other AWS services, making it an ideal choice for building dynamic applications with minimal operational overhead.