AWS Lambda is a serverless service that allows you to run code without managing servers. It automatically scales with traffic and only charges when your code is executed, making it ideal for applications like backend APIs.
Lambda Function is a piece of code (written in Node.js, Python, etc.) deployed on AWS Lambda to handle specific tasks, like retrieving data from DynamoDB or handling API requests.
In this workshop, we will create two Lambda functions:
getPosts
: Retrieves a list of posts from the BlogPosts
table in DynamoDB.createPost
: Add new posts to the BlogPosts
table.@aws-sdk/client-dynamodb
) to optimize performance.getPosts
In the Create function section:
Function name: Enter getPosts
.
Runtime: Select Node.js 20.x.
Role: Select Use an existing role and select lambda-blog-role
(created in the IAM step).
Click Create function.
getPosts
index.mjs
with the following code:import { DynamoDBClient, ScanCommand } from '@aws-sdk/client-dynamodb';
const dynamodb = new DynamoDBClient({});
export const handler = async () => {
const params = {
TableName: process.env.TABLE_NAME
};
try {
const data = await dynamodb.send(new ScanCommand(params));
return {
statusCode: 200,
body: JSON.stringify(data.Items || []),
headers: { 'Content-Type': 'application/json' }
};
} catch (err) {
console.error('Error:', err);
return {
statusCode: 500,
body: JSON.stringify({ error: 'Could not retrieve posts' })
};
}
};
Add environment variables: In the Configuration → Environment variables tab, select Edit. Add: TABLE_NAME = BlogPosts. Click Save.
Repeat steps 2-3 to create a new function with: Function name: createPost. Runtime: Node.js 20.x. Role: lambda-blog-role.
Replace the code in index.mjs with:
import { DynamoDBClient, PutItemCommand } from '@aws-sdk/client-dynamodb';
import { marshall } from '@aws-sdk/util-dynamodb';
const dynamodb = new DynamoDBClient({});
export const handler = async (event) => {
const body = JSON.parse(event.body || '{}');
const params = {
TableName: process.env.TABLE_NAME,
Item: marshall({
postId: body.postId || Date.now().toString(),
title: body.title || 'Untitled',
content: body.content || '',
createAt: new Date().toISOString()
})
};
try {
await dynamodb.send(new PutItemCommand(params));
return {
statusCode: 200,
body: JSON.stringify({ message: 'Post created successfully' }),
headers: { 'Content-Type': 'application/json' }
};
} catch (err) {
console.error('Error:', err);
return {
statusCode: 500,
body: JSON.stringify({ error: 'Could not create post' })
};
}
};
Add environment variable TABLE_NAME = BlogPosts as in step 4.
To add dependencies @aws-sdk/client-dynamodb and @aws-sdk/util-dynamodb, create a package.json file in the source code directory:
{
"name": "lambda-blog",
"version": "1.0.0",
"type": "module",
"dependencies": {
"@aws-sdk/client-dynamodb": "^3.0.0",
"@aws-sdk/util-dynamodb": "^3.0.0"
}
}
Make sure to use ES Module (index.mjs) and handler is index.handler. The .zip file must include node_modules to avoid missing dependency errors. The environment variable TABLE_NAME must match the DynamoDB table name (BlogPosts).
In the interface of each function, select the Test tab:
For getPosts, create an event with empty JSON {}.
For createPost, create a sample event:{
"body": "{\"postId\": \"1\", \"title\": \"Test Post\", \"content\": \"This is a test post.\"}"
}