In this tutorial, we are going to connect together everything we learned in the previous AWS tutorials and make a static website call API Gateway which then calls our Lambda Functions which then finally writes to or reads from our DynamoDB, whoa sounds like a lot, but it isn’t we already learn everything we needed to from our previous tutorials:

As always if you prefer video tutorials be sure to check out my tutorial on YouTube.

The Static Website

So what we are going to make is very simple, this site on load calls a GET function to AWS API Gateway which then calls our Lambda function which reads from the Message table in DynamoDB. When I fill it out this form and click submit the site makes a POST call to API Gateway which calls our Lambda Function which then writes to our DynamoDB. The following code is the HTML and JavaScript we will be using as the frontend of this tutorial:

<html>
	<script>
		async function getMessages() {
			fetch( 'https://otmbnk4ysl.execute-api.us-east-1.amazonaws.com/prod/message',  {
				method: 'GET'
			  })
			.then(response => response.json())
			.then((response) => {
                console.log(response.body);
                response.body.forEach(element => {
                    document.getElementById("messages").innerHTML += "<p>"+element.message+"</p>"; // Adds each message to div
                });
			});
        }
		async function submitMessage() {
            var name = document.getElementById("name").value;
            var email = document.getElementById("email").value;
            var message = document.getElementById("message").value;
			fetch( 'https://otmbnk4ysl.execute-api.us-east-1.amazonaws.com/prod/message',  {
                method: 'POST',
                body: JSON.stringify({
                    "name": name,
                    "email": email,
                    "message": message
                })
			})
			.then(response => response.json())
			.then((response) => {
				console.log(response);
                document.getElementById("messages").innerHTML += "<p>"+message+"</p>"; // Add new message to message list
			});
		}
        getMessages(); // Calls get message on load
    </script>   
    <head>  
        <title>Test Form</title>
    </head>
    <body>
        <form onsubmit="submitMessage();return false;">
            <label for="name">Name:</label><br>
            <input type="text" id="name" name="name" value=""/><br>
            <label for="email">Email:</label><br>
            <input type="text" id="email" name="email" value=""/><br>
            <label for="message">Message:</label><br>
            <textarea id="message" name="message" value="" rows="10" cols="30"></textarea><br><br>
            <input type="submit" value="Submit">
      </form> 
      <strong>Messages from DynamoDB</strong>
      <div id="messages">

      </div>
	</body>
</html>

There are two JavaScript functions getMessages() and submitMessage(), which will call our API’s GET and POST that we set up later in this tutorial. In this tutorial you do not need to put this in your S3 bucket, but if you like to please refer to Setting Up a Static Website Using AWS S3.

Read Messages

Let’s first review our ReadMessage lambda function. This is the Lambda function we already created when following the How to Read and Write to DynamoDB using AWS Lambda tutorial.

// 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();
}

We do not need to make any changes to this code. In fact, all we need to do is set up our API Gateway to call this Lambda function. If you have not already, follow the How to Connect AWS API Gateway to Lambda tutorial to set up your AWS API Gateway.

AWS API Gateway

At the AWS API Resource click Actions -> Create Resource

Create Resource

Name your resource “message” and click “Create Resource”

Name resource “message”

Now we are going to add our GET call and connect our ReadMessage Lambda function to it. Make sure your message resource is selected and click “Actions” again and chose “Create Method”. Make the method a GET as we are just reading information and making no modifications. Now our GET method has been created and you will be in the GET – Setup screen. In GET – Setup screen select your integration type to be a Lambda Function, your Lambda region should be where you created your Lambda functions, and then type in the Lambda function name (in this case ReadMessage), then click the “Save” button.

Modify GET – Setup to connect to Lambda

Then you need to enable CORS for the GET method. Click the “Actions” dropdown and select “Enable CORS”. By default it already has the Access-Control-Allow-Origin set to all, specify a domain otherwise click “Enabled CORS and replace existing CORS headers”.

Now you need to deploy your API. Inside your AWS API click the “Action” dropdown and click “Deploy API”. If you do not have a stage already select “[New Stage]” and name the Stage “Prod” and click “Deploy”. You now have successfully deployed your API, and you are provided an invoke URL, where you can call your API (which then calls your Lambda function).

If you open the static file from earlier you should now receive messages from the DynamoDB.

Write Messages

Now that we are reading from our DynamoDB lets now focus on writing to our DynamoDB. In this tutorial, we are going to pass some values from our textbox on our static website and send them to our Lamba function, which will then write them to the DynamoDB server. We are going to update our WriteMessage Lambda code to the following:

// 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;
    if(event.name && event.email && event.message) {
        // Handle promise fulfilled/rejected states
        await createMessage(requestId, event).then(() => {
            callback(null, {
                statusCode: 201,
                body: '',
                headers: {
                    'Access-Control-Allow-Origin' : '*'
                }
            });
        }).catch((err) => {
            console.error(err)
        })
    } else {
        callback(null, {
            statusCode: 400,
            body: 'Bad Request',
            headers: {
                'Access-Control-Allow-Origin' : '*'
            }
        });
    }
};

// Function createMessage
// Writes message to DynamoDb table Message 
function createMessage(requestId, event) {
    
    const params = {
        TableName: 'Message',
        Item: {
            'messageId' : requestId,
            'name' : event.name,
            'email' : event.email,
            'message' : event.message
        }
    }

    return ddb.put(params).promise();
}

Our AWS Lambda function now expects the following JSON body:

{
   "name":"string",
   "email":"string",
   "message":"string"
}

The HTML code provided earlier already sends POST to the API Gateway with the provide JSON body. So lets set up our POST call on API Gateway.

AWS API Gateway

Go back to the API Gateway and make sure your message resource is selected and click “Actions” again and chose “Create Method”. Make the method a POST as we are writing a new object to our DynamoDB. Now our POST method has been created and you will be in the POST – Setup screen. In POST – Setup screen select your integration type to be a Lambda Function, your Lambda region should be where you created your Lambda functions, and then type in the Lambda function name (in this case WriteMessage), then click the “Save” button.

Modify POST– Setup to connect to Lambda

You can test the API here use the above JSON and see if it writes to your DynamoDB.

Then you need to enable CORS for the POST method. Click the “Actions” dropdown and select “Enable CORS”. By default it already has the Access-Control-Allow-Origin set to all, specify a domain otherwise click “Enabled CORS and replace existing CORS headers”.

Now you need to redeploy your API. Inside your AWS API click the “Action” dropdown and click “Deploy API”. Select the “Prod” stage and click “Deploy”. You now have successfully deployed your API, and you are provided an invoke URL, where you can call your API (which then calls your Lambda function).

If you open the static file from earlier you should now submit a message and it will write to DynamoDB.

Congratulations you’ve just created a static website which calls API Gateway which then calls our Lambda Functions which then finally writes to or reads from our DynamoDB.