Build Your First AWS Web Application

Build Your First AWS Web Application

Objective

Create a simple AWS Web Application with AWS Amplify, API Gateway, Lambda, DynamoDB and IAM.

  • Create a web application with AWS Amplify

  • Deploy a Lambda function to do math

  • Invoke the math function with API Gateway

  • Store the math result in the DynamoDB table

  • Modify your web app to invoke your API

  • Clean up resources

Application Architecture

The below diagram shows the services used in this lab and how they are connected.

Steps

1. Create a Web Application with AWS Amplify.

a. Create an index.html file and zip it up. You can copy the below HTML code.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Addition Math!</title>
</head>

<body>
    Addition Math!
</body>
</html>

b. From the AWS Amplify console, choose “Amplify Hosting (host your web app)” to create a new app, choose “Deploy without Git Provider” and continue, give an app name and environment name, and use “Drag and drop” to upload the zipped index.html file. Save and deploy.

c. Open a new tab with the Domain.

d. You see below a simple page.

2. Deploy a Lambda Function to do math.

a. Navigate to AWS Lambda, create a function from scratch, “AdditionMath” as the function name, Runtime with the latest Python, then create the function.

b. Update the lambda function and save (Ctrl-S).

You can copy the code below:

# import the JSON utility package
import json

# define the handler function that the Lambda service will use an entry point
def lambda_handler(event, context):

# extract the two numbers from the Lambda service's event object
    mathResult = int(event['firstnumber']) + int(event['secondnumber'])

    # return a properly formatted JSON object
    return {
    'statusCode': 200,
    'body': json.dumps('Your result is ' + str(mathResult))
    }

c. Deploy. Configure the test event and save.

d. Then click on the “Test” button to run the test.

e. You get the test result.

3. Invoke the Math Function with API Gateway.

a. Navigate to API Gateway, create “REST API” (not private).

b. Select “Resources” and select “/”, click on “Actions” then select “create method”. Pick “POST” from the drop-down list. Then click on the little check mark.

c. Then you will see this. Then specify the Lambda Function you created and save.

d. After save, you will see this.

e. Next, enable CORS (cross-origin resource sharing). Select “POST”, then click on “Actions” then pick “Enable CORS”.

f. Deploy the API. Click on “Actions” and choose “Deploy API”.

g. Copy this invoke URL and save it somewhere. Will need this later so keep it handy.

h. Click on “Resources”, then “POST”, then click on the lighting bolt.

i. Test the POST method. Add the Request Body.

j. Click on “Test” at the bottom. Test successfully.

4. Store the math function result in the DynamoDB table.

a. Navigate to DynamoDB, create a table, and give the table name and “ID” as the Partition key. Leave everything else the same.

b. Save the ARN somewhere handy.

c. Give the lambda permission to write to the DynamoDB table. Navigate to the Lambda function, click on “Configuration”, then “Permission”, then click on the Role name.

d. It will open up a new tab. Click on “Add Permissions”.

e. Then choose “Create Inline Policy”, click on the “JSON” tab and copy the JSON code. Make sure to put your DynamoDB table ARN in the “Resource” section.

You can copy the JSON policy:

{
"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"
    }
    ]
}

f. Review policy. Give a name.

g. Create the policy. Then you see the policy added.

h. Now change the lambda function to store the result in the DynamoDB table. Navigate to the Lambda function, then select “Code”. Replace the lambda function. Make sure to update the table name. Save and Deploy.

you can copy the code below:

# import the JSON utility package
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('AdditionMathDB')
# 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 an entry point
def lambda_handler(event, context):

# extract the two numbers from the Lambda service's event object
    mathResult = int(event['firstnumber']) + int(event['secondnumber'])

# write result and time to the DynamoDB table using the object we instantiated and save response in a variable
    response = table.put_item(
        Item={
            'ID': str(mathResult),
            'LatestGreetingTime':now
            })

# return a properly formatted JSON object
    return {
    'statusCode': 200,
    'body': json.dumps('Your result is ' + str(mathResult))
    }

i. Test the lambda function with the same test event.

j. The DynamoDB table has a stored lambda function test result.

5. Modify Your Web App to Invoke Your API.

a. Modify index.html and use the API invoke URL you saved. And zip it up.

You can copy the code (note: replace with your API URL):

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Addition Math!</title>
    <!-- Styling for the client UI -->
    <style>
    h1 {
        color: #FFFFFF;
        font-family: system-ui;
        margin-left: 20px;
        }
    body {
        background-color: #222629;
        }
    label {
        color: #86C232;
        font-family: system-ui;
        font-size: 20px;
        margin-left: 20px;
        margin-top: 20px;
        }
     button {
        background-color: #86C232;
        border-color: #86C232;
        color: #FFFFFF;
        font-family: system-ui;
        font-size: 20px;
        font-weight: bold;
        margin-left: 30px;
        margin-top: 20px;
        width: 140px;
        }
     input {
        color: #222629;
        font-family: system-ui;
        font-size: 20px;
        margin-left: 10px;
        margin-top: 20px;
        width: 100px;
        }
    </style>
    <script>
        // callAPI function that takes the firstnumber and secondnumber as parameters
        var callAPI = (firstnumber,secondnumber)=>{
            // instantiate a headers object
            var myHeaders = new Headers();
            // add content type header to object
            myHeaders.append("Content-Type", "application/json");
            // using built in JSON utility package turn object to string and store in a variable
            var raw = JSON.stringify({"firstnumber":firstnumber,"secondnumber":secondnumber});
            // create a JSON object with parameters for API call and store in a variable
            var requestOptions = {
                method: 'POST',
                headers: myHeaders,
                body: raw,
                redirect: 'follow'
            };
            // make API call with parameters and use promises to get response
            fetch("https://tkbkiu4ufj.execute-api.us-east-1.amazonaws.com/dev", requestOptions)
            .then(response => response.text())
            .then(result => alert(JSON.parse(result).body))
            .catch(error => console.log('error', error));
        }
    </script>
</head>
<body>
    <h1>ADDITION MATH!</h1>
    <form>
        <label>first number:</label>
        <input type="text" id="firstnumber">
        <label>second number:</label>
        <input type="text" id="secondnumber">
        <!-- set button onClick method to call function we defined passing input values as parameters -->
        <button type="button" onclick="callAPI(document.getElementById('firstnumber').value,document.getElementById('secondnumber').value)">CALCULATE</button>
    </form>
</body>
</html>

b. Navigate to AWS Amplify. Update the index.html zip file. It will automatically redeploy the app.

c. Open the domain.

d. You get a new tab as below. Enter 10 and 5 and then click on the “CALCULATE” button. The result 15 popped up.

6. All done. A simple web application is created to do the math addition.

7. Clean Up Resources.

a. Go to the DynamoDB console and delete your table and confirm.

b. Go to the API Gateway console and delete the API and confirm.

c. Go to the Lambda console and delete the Lambda function and confirm.

d. Go to Amplify console and delete the app and confirm.

Accomplished

Connecting AWS Amplify, API Gateway, Lambda, DynamoDB and IAM services together created a basic end-to-end web application.

References:

AWS tutorial: Build a Basic Web Application on AWS (amazon.com)

Youtube by: TinyTechnicalTutorials