Build a Basic Web Application


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.

 Minimum time to complete

10 minutes

 Last updated

April 4, 2023


    1. Log in to the Amazon DynamoDB console.
    2. Make sure you create your table in the same Region in which you created the web app in the previous module. You can see this at the very top of the page, next to your account name.
    3. Choose the orange Create table button.
    4. Under Table name, enter HelloWorldDatabase.
    5. In the Partition key field, enter ID. The partition key is part of the table's primary key.
    6. Leave the rest of the default values unchanged and choose the orange Create table button.
    7. In the list of tables, select the table name, HelloWorldDatabase.
    8. In the General information section, show Additional info by selecting the down arrow.

    9. Copy the Amazon Resource Name (ARN). You will need it later in this module.

    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. Select 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 the function in.
    3. We'll be adding permissions to our function so it can use the DynamoDB service, and we will be using AWS Identity and Access Management (IAM) to do so.
    4. Select the Configuration tab and select Permissions from the right side menu.
    5. In the Execution role box, under Role name, choose the link. A new browser tab will open.
    6. In the Permissions policies box, open the Add permissions dropdown and select Create inline policy.
    7. Select the JSON tab.
    8. Paste the following policy in the text area, taking care to replace your table's ARN in the Resource field in 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. Choose the blue Review Policy button.

    11. Next to Name, enter HelloWorldDynamoPolicy.

    12. Choose the blue Create Policy button.

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

    • Python
      1. Select the Code tab and select your function from the navigation pane 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 time 
      import time
      # import two packages to help us with dates and date formatting
      # create a DynamoDB object using the AWS SDK
      dynamodb = boto3.resource('dynamodb')
      # use the DynamoDB object to select our table
      table = dynamodb.Table('HelloWorldDatabase')
      # define the handler function that the Lambda service will use as an entry point
      def lambda_handler(event, context):
       # Get the current GMT time
          gmt_time = time.gmtime()
          # store the current time in a human readable format in a variable
          # Format the GMT time string
          now = time.strftime('%a, %d %b %Y %H:%M:%S +0000', gmt_time)
      # 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. Choose the Deploy button at the top of the code editor

    • JavaScript
      1. Select the Code tab and select your function from the navigation pane 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. Choose the Deploy button at the top of the code editor.

    • Java
      1. Select 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
    1. Choose 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 left-hand navigation pane, select Tables > Explore items.
    5. Select HelloWorldDatabase, which we created earlier in this module.
    6. Select 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 or 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