In this tutorial, you will learn how to read and write to DynamoDB using AWS Lambda. You will learn how to create a DynamoDB table and create node.js functions that read and write to the DynamoDB table. If you prefer video tutorials be sure to check out my tutorial on YouTube.

Create a Table in DynamoDB

DynamoDB is a schema-less database, this means the database doesn’t have a fixed data structure.

From your AWS console, navigate to the DynamoDB service (either search for DynamoDB or under Database click DynamoDB). On the DynamoDB dashboard click the “Create table” button.

Click the "Create table" button.
DynamoDB Dashboard

This will bring you to the Create DynamoDB Table wizard. As DynamoDB is a schema-less database, you only need to define the table’s name and primary key. The table’s primary key uniquely identify items, partition the data, and sort data within each partition. In this example, we will name our table “Message” and the primary key will be “messageId”, “messageId” will be a UUID so we will set its type to “string”. A UUID is a universally unique identifier and is a 128-bit number. Keep everything else set to their default values and click the “Create” button.

Create DynamoDB Wizard
Create DynamoDB Wizard

This will navigate you to your newly created table. Scroll down on the overview tab, under table details there is an Amazon Resource Name (ARN), you will need this value if you want to restrict a role to ONLY be able to access this table and not have a global role. We have successfully created our DynamoDB table, lets now make our lambda function.

Write to DynamoDB from Lambda

On the AWS Lamba dashboard click “Create function”.

AWS Lambda Dashboard
AWS Lambda Dashboard

Select “Author from scratch” and name the function “WriteMessage”, make sure Node.js be selected for the runtime. Also, keep all permissions as the default values. Click the “Create Function” button.

Create Function Setup
Create Function Setup

We are now in our newly created AWS Lambda Function. The lambda function has a prefilled out Node.js function that returns back “Hello from Lamba!” We are going to update this code so we can write to the DynamoDB. Here is the code we will use:

// Loads in the AWS SDK
const AWS = require('aws-sdk'); 

// Creates the document client specifing the region 
// The tutorial's table is 'in us-east-1'
const ddb = new AWS.DynamoDB.DocumentClient({region: 'us-east-1'}); 

exports.handler = async (event, context, callback) => {
    // Captures the requestId from the context message
    const requestId = context.awsRequestId;

    // Handle promise fulfilled/rejected states
    await createMessage(requestId).then(() => {
        // If success return 201
        callback(null, {
            statusCode: 201,
            body: '',
            headers: {
                'Access-Control-Allow-Origin' : '*'
            }
        });
    }).catch((err) => {
        // If an error occurs write to the console
        console.error(err)
    })
};

// Function createMessage
// Writes message to DynamoDb table Message
// Returns promise
function createMessage(requestId) {
    const params = {
        TableName: 'Message',
        Item: {
            'messageId' : requestId,
            'message' : 'Hello from lambda'
        }
    }
    return ddb.put(params).promise();
}

Replace the code in index.js with this code and save. We are not done yet, if we try to test this Lambda function we will get an AccessDeniedException. This due to the role that Lambda function uses does not have permission to access DynamoDB. Let’s update the role’s permission.

Update WriteMessage Role Permissions

Scroll up to the top of your AWS Lambda Function view and click the permissions tab.

AWS Lambda Permissions Tab
AWS Lambda Permissions Tab

From here click the execution role link. This will bring you to the IAM Management Console for the role. On this screen expand your AWSLambdaBasicExecutionRole policy and click edit policy.

IAM Management Console for WriteMessage Role with AWSLambdaBasicExecutionRole expanded
IAM Management Console with AWSLambdaBasicExecutionRole expanded

In the edit AWSLambdaBasicExecutionRole wizard, click “Add additional permissions”

Click  "Add additional permissions"
Click “Add additional permissions”

For the service chose DynamoDB. In this example, we are going to give permissions to have all the DynamoDB actions, but you can restrict the role to only do a specific action (this is a good idea to do for security). W are going to also give permission to all resources, but you can give access to a specific table (aka resource). If you want to restrict to a specific table, under your DynamoDB table details there is an Amazon Resource Name (ARN), you can use this to restrict a role to ONLY be able to access this table and not have a global role.

New Permission Settings
New Permission Settings

Click “Review policy”. The DynamoDB has now been added to the AWSLambdaBasicExecutionRole policy. Click “Save changes”. This will navigate you back to the IAM Management Console for the role and you should see DynamoDB as part of the policy.

DynamoDB now part of the Policy
DynamoDB now part of the Policy

Go back to your WriteMessage Lambda function and test it. You should now get a success message.

Test the WriteMessage Lambda Function Again
Test the WriteMessage Lambda Function Again

Navigate to you DynamoDB and go to the items tab, here you will see your message from the AWS Lambda Function.

The message has been added to the DynamoDB table
The message has been added to the DynamoDB table

Read from DynamoDB from Lambda

Repeat the steps above to create a function and name this lambda function ReadMessage. After creating the function you will be brought into your newly created AWS Lambda Function. It will already have a prefilled out Node.js function that returns back “Hello from Lamba!” Let’s update this code so we can read from the DynamoDB. Here is the code we will use:

// Loads in the AWS SDK
const AWS = require('aws-sdk'); 

// Creates the document client specifing the region 
// The tutorial's table is 'in us-east-1'
const ddb = new AWS.DynamoDB.DocumentClient({region: 'us-east-1'}); 

exports.handler = async (event, context, callback) => {
    // Handle promise fulfilled/rejected states
    await readMessage().then(data => {
        // Writes each item to the console
        data.Items.forEach(function(item) {
            console.log(item.message)
        });
        callback(null, {
            // If success return 200, and items
            statusCode: 200,
            body: data.Items,
            headers: {
                'Access-Control-Allow-Origin': '*',
            },
        })
    }).catch((err) => {
        // If an error occurs write to the console
        console.error(err);
    })
};

// Function readMessage
// Reads 10 messages from the DynamoDb table Message
// Returns promise
function readMessage() {
    const params = {
        TableName: 'Message',
        Limit: 10
    }
    return ddb.scan(params).promise();
}

The permissions for the lambda function roles will need to be updated as well. You can updated the ReadMessage role to only be able to read from the table Message, or you can change the role the Lambda function executes with. Let’s about the Lambda function to use the WriteMessage Role.

On the AWS Lambda Function view scroll up to the top and click the permissions tab. Go to the Execution role section click the “Edit” button.

On the Execution role section click the "Edit" button
On the Execution role section click the “Edit” button

You will be brought to the Edit basic settings under Existing role, chose the WriteMessage role, and click the “Save” button.

Update to WriteMessage role, and click save
Update to WriteMessage role, and click save

Now you can test your Lamba function and you should successfully be reading from the DynamoDB table.

Congratulations, you just learn how to read and write to DynamoDB using AWS Lambda. If you plan to use this set to connect AWS API Gateway be sure to check out my tutorial on how to connect AWS API Gateway to Lambda.