Getting Started with AWS

Build a Basic Web Application

Deploy a web application and add interactivity with an API and a database

Module 4: Create a Data Table

In this module you will create a DynamoDB table and enable your Lambda function to store data in it.

Introduction

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. In order to do this, we will use the AWS SDK (Python, JavaScript, or Java) from our Lambda function.

What You Will Learn

  • 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 A non-relational database does 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 SDK stands for "Software Development Kit." AWS SDKs 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 (e.g., service, user, group) has access to.

 Time to Complete

10 minutes

Implementation

  • 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 blue "Create table" button.
    4. Next to "Table name" type in HelloWorldDatabase.
    5. In the "Primary Key" field type in ID.
    6. Click the blue "Create" button.
    7. Copy the table's "Amazon Resource Name (ARN)" from the right hand panel (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").
    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 "Permissions" tab.
    5. In the "Execution role" box click on the role. A new browser tab will open.
    6. Click on "Add inline policy" on the right of the "Permissions policies" box.
    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": [
                "dynamodb:PutItem",
                "dynamodb:DeleteItem",
                "dynamodb:GetItem",
                "dynamodb:Scan",
                "dynamodb:Query",
                "dynamodb:UpdateItem"
            ],
            "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
    • JavaScript
    • Java
    • Python
      1. Click the "Configuration" tab
      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(
              Item={
                  'ID': name,
                  'LatestGreetingTime':now
                  })
      # return a properly formatted JSON object
          return {
              'statusCode': 200,
              'body': json.dumps('Hello from Lambda, ' + name)
          }

      3. Click the orange "Save" button at the top of the page.

    • JavaScript
      1. Click the "Configuration" tab
      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 = {
              TableName:'HelloWorldDatabase',
              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 orange "Save" button at the top of the page.

    • 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 com.example.app.SavePersonHandler::handleRequest.
      4. Click the orange "Save" button at the top of the page.
  • Test the Changes
    1. Click the white "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. Click on "Tables" on the left hand navigation bar.
    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 should appear here. If you have been using our examples, the item ID will be "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 us look at our current architecture:

Full Stack tutorial Module Four app arch

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 API Gateway.

Was this module helpful?

Thank you
Please let us know what you liked.
Sorry to disappoint you
Is something out-of-date, confusing or inaccurate? Please help us improve this tutorial by providing feedback.

Add Interactivity to Website