Module 4: Create a Data Table

In this module, you will create an Amazon DynamoDB table and enable your Lambda function to store data in it


In this module, we will create a table to persist data using Amazon DynamoDB. DynamoDB is a key-value database service, so we do not need to create a schema for our data. It has consistent performance at any scale and there are no servers to manage when using it.

Additionally, we will use the AWS Identity and Access Management (IAM) service to securely give our services the required permissions to interact with each other. Specifically, we are going to allow the Lambda function we created in module two to write to our newly created DynamoDB table using an IAM policy. To do this, we will use the AWS SDK (Python, JavaScript, or Java) from our Lambda function.

What you will accomplish

In this module, you will:
  • Create a DynamoDB table using the AWS Management Console
  • Create a role and manage permissions with IAM
  • Write to a DynamoDB table using the AWS SDK (Python, JavaScript, or Java)

Key concepts

Persisting data — Storing data so we can access it in the future, independently from program execution.

Non-relational database — Non-relational databases do not use a tabular schema of rows and columns. Instead, they use a storage model that is optimized for the specific requirements of the type of data being stored.

Key-value database — A type of non-relational database that stores data as a collection of key-value pairs in which a key serves as a unique identifier.

Primary key — The value that will identify each piece of data in a DynamoDB table. This value will also serve to partition the table to make it scalable.

Schema — The organization of data that serves as a blueprint for how a database should be constructed.

AWS SDK — AWS SDKs (software development kits) provide a set of tools, libraries, documentation, code samples, processes, and guides that allow developers to create software applications on a specific platform.

IAM policy — A document that defines what AWS resources an entity, such as a service, user, or group, has access to.

 Time to complete

10 minutes


  • Create a DynamoDB Table
    1. Log into the Amazon DynamoDB Console.
    2. Make sure you note what region you are creating your function in. You can see this at the very top of the page, next to your account name.
    3. Click the orange "Create table" button.
    4. Under "Table name" type in HelloWorldDatabase.
    5. In the "Partition key" field type in ID. The partition key is part of the table's primary key.
    6. Click the orange "Create table" button.
    7. In the list of tables, click on the table name, HelloWorldDatabase.
    8. Expand the "Additional info" panel.
    9. Copy the "Amazon Resource Name (ARN)." You will need it later on in this module.
  • Create and Add IAM Policy to Lambda Function
    1. Now that we have a table, let's edit our Lambda function to be able to write data to it. In a new browser window, open the AWS Lambda Console.
    2. Click on the function we created in Module Two (if you have been using our examples, it will be called "HelloWorldFunction"). If you don't see it, check the region dropdown in the upper right next to your name to ensure you're in the same region you created it in.
    3. We'll be adding permissions to our function so it can use the DynamoDB service, and we'll be using AWS Identity and Access Management (IAM) to do so.
    4. Click on the "Configuration" tab and select "Permissions" from the right side menu.
    5. In the "Execution role" box, under "Role name," click on the link. A new browser tab will open.
    6. In the "Permissions policies" box, open the "Add permissions" dropdown and click on "Create inline policy".
    7. Click on the "JSON" tab.
    8. Paste the following policy in the text area, taking care to replace your table's ARN in the "Resource" field on line 15:
    "Version": "2012-10-17",
    "Statement": [
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
            "Resource": "YOUR-TABLE-ARN"

    9. This policy will allow our Lambda function to read, edit or delete items, but restrict it to only be able to do so in the table we created.

    10. Click the blue "Review Policy" button.

    11. Next to "name" type in HelloWorldDynamoPolicy.

    12. Click the blue "Create Policy" button.

    13. You can now close this browser tab and go back to the tab for your Lambda function.

  • Modify Lambda Function to Write to DynamoDB table
    • Python
      1. Click on the "Code" tab and select your function from the navigation panel on the left side of the code editor.
      2. Replace the code for your function with the following:
      # import the json utility package since we will be working with a JSON object
      import json
      # import the AWS SDK (for Python the package name is boto3)
      import boto3
      # import two packages to help us with dates and date formatting
      from time import gmtime, strftime
      # create a DynamoDB object using the AWS SDK
      dynamodb = boto3.resource('dynamodb')
      # use the DynamoDB object to select our table
      table = dynamodb.Table('HelloWorldDatabase')
      # store the current time in a human readable format in a variable
      now = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
      # define the handler function that the Lambda service will use as an entry point
      def lambda_handler(event, context):
      # extract values from the event object we got from the Lambda service and store in a variable
          name = event['firstName'] +' '+ event['lastName']
      # write name and time to the DynamoDB table using the object we instantiated and save response in a variable
          response = table.put_item(
                  'ID': name,
      # return a properly formatted JSON object
          return {
              'statusCode': 200,
              'body': json.dumps('Hello from Lambda, ' + name)

      3. Click the "Deploy" button at the top of the code editor

    • JavaScript
      1. Click on the "Code" tab and select your function from the navigation panel on the left side of the code editor.
      2. Replace the code for your function with the following:
      // Include the AWS SDK module
      const AWS = require('aws-sdk');
      // Instantiate a DynamoDB document client with the SDK
      let dynamodb = new AWS.DynamoDB.DocumentClient();
      // Use built-in module to get current date & time
      let date = new Date();
      // Store date and time in human-readable format in a variable
      let now = date.toISOString();
      // Define handler function, the entry point to our code for the Lambda service
      // We receive the object that triggers the function as a parameter
      exports.handler = async (event) => {
          // Extract values from event and format as strings
          let name = JSON.stringify(`Hello from Lambda, ${event.firstName} ${event.lastName}`);
          // Create JSON object with parameters for DynamoDB and store in a variable
          let params = {
              Item: {
                  'ID': name,
                  'LatestGreetingTime': now
          // Using await, make sure object writes to DynamoDB table before continuing execution
          await dynamodb.put(params).promise();
          // Create a JSON object with our response and store it in a constant
          const response = {
              statusCode: 200,
              body: name
          // Return the response constant
          return response;

      3. Click the "Deploy" button at the top of the code editor

    • Java
      1. Click the "Configuration" tab
      2. Go to "Function code" and upload the following JAR file. (For the purposes of this tutorial, we will skip the creation of the deployment package.)
      3. Update the "Handler" to
      4. Click the orange "Save" button at the top of the page.
  • Test the Changes
    1. Click the orange "Test" button.
    2. You should see an "Execution result: succeeded" message with a green background.
    3. In a new browser tab, open the DynamoDB Console.
    4. In the lefthand navigation bar, click on "Tables > Explore items".
    5. Click on HelloWorldDatabase, which we created earlier in this module.
    6. Click on the "Items" tab on the right.
    7. Items matching your test event appear under "Items returned." If you have been using our examples, the item ID will be "Hello from Lambda, Ada Lovelace".
    8. Every time your Lambda function executes, your DynamoDB table will be updated. If the same name is used, only the time stamp will change.

Application architecture

With module four complete, let's look at our current architecture:

Architecture diagram showing services hosted in AWS Cloud, with connections shown from external users to interconnected AWS services.

We added two services in this module: DynamoDB (for storage) and IAM (for managing permissions securely). Both are connected to our Lambda function, so that it can write to our database. The final step is to add code to our client to call the API Gateway.

Was this page helpful?

Add Interactivity to Web App