How-to-Connect-a-Web-App-to-a-Database-Using-AWS

How to Connect a Web App to a Database Using AWS

Posted in

In today’s decentralized world, web apps are more important than ever. Web apps are endlessly useful for remote workers, for one thing, as it gives your entire enterprise access to the same software. They’re also platform agnostic, as they run through an internet browser, so you don’t have to create multiple versions for different platforms. They don’t even need to be installed, saving your development team the trouble of unnecessary software installation.

Creating web apps can involve a bit of a learning curve, however. They require a responsive UI, for one thing. They must be hosted and connected to data on the backend as well. Creating a web app also requires choosing the best tech stack for your project.

AWS is a good choice for web application development as it handles many of these logistics for you. With that in mind, below, we’ll walk through how to create your first web app and connect it to a database using AWS.

Create a Web App

To start, we’ll use AWS Amplify to create the static resources for our web app. These include HTML, CSS, JavaScript, images, and files. AWS Amplify makes hosting static websites easy and painless and enables accessing the resulting URL.

We’re going to use AWS Amplify to host a simple Hello, World app.

To start, open your preferred text editor (we like Notepad++ and then input the following code to create a simple HTML file.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello World</title>
</head>

<body>
    Hello World
</body>
</html>

Save this file as index.html. Then create a .zip file containing only index.html.

Next, open the AWS Amplify console. (Note: you’ll need to create an AWS account if you don’t already have one).

Then, select Get Started. Then click the orange Get Started button beneath Host your web app. Then choose to Deploy without Git provider.

Your screen should look like this:

Click Continue.

Name your app GettingStarted.

In the field for Environment name, input dev.

Select the Drag and drop method. Then drag index.zip and then click Save and deploy.

Test Web App

Now we’re going to check and make sure the web app is working.

First, find Domain management under App settings.

In the Domain management section, find the URL. Copy and paste the URL into your browser. If everything is working correctly, you should see Hello World.

Create a Serverless Function

Now we’ll make our web app do something. We’re going to write a chunk of code in Python and JavaScript to add some interactivity to the web app. We’ll then turn that code into an AWS Lambda function.

Start by opening the AWS Lambda console. Make sure you create your Lambda function in the same region you chose for your web app.

Click the Create function button.

In the Function name, input HelloWorldFunction.

Select Python 3.8 from the runtime drop-down menu under the Other supported options. Then click the orange Create function button in the bottom-right corner.

You should see the message “Successfully created the function HelloWorldFunction.”

Now we’re going to modify the Lambda function. In the Lambda code editor, replace the code with the following:

# import the JSON utility package since we will be working with a JSON object
import json
# 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
    name = event['firstName'] +' '+ event['lastName']
# return a properly formatted JSON object
    return {
    'statusCode': 200,
    'body': json.dumps('Hello from Lambda, ' + name)
    }

Save the changes in the File dropdown menu and then Deploy the Lambda function.

Next, we’re going to test the Lambda function.

Click the orange Test button. Then choose Configure test event.

In the Event name field, input HelloWorldTestEvent. Then replace the default JSON in the Event JSON window with the following:

{
"firstName": "Ada",
"lastName": "Lovelace"
}

Then click Create event.

Now you’re ready to test your Lambda function. Click the orange Test button. If everything’s working correctly, you should see this result returned:

{
  "statusCode": 200,
  "body": "\"Hello from Lambda, Ada Lovelace\""
}

As you can see, the Lambda function returns the objects firstName and lastName as well as the phrase “Hello From Lambda.”

Now we’ll connect our web app to the Lambda function using an AWS API.

Start by opening the AWS API Gateway. In the Choose an API type section, find the REST API option and choose Build.

Under the Create new API section, select New API.

In the API name field, input HelloWorldAPI.

Select Edge-Optimized from the Endpoint Type dropdown menu, as it’s the best option for decentralized development teams.

Click the CREATE API button.

The window should look like this:

Create a New Resource

In the left navigation window, select Resources. Make sure the “/” option is selected. Then select Create Method from the Actions dropdown menu.

Choose POST from the new dropdown menu under Resources. Select Lambda Function from the Integration type. Make sure you’ve got the same region selected as you used for your web app and Lambda function.

In the Lambda Function field, input HelloWorldFunction, the name of the function we created earlier. Then click the blue Save button.

You should see a pop-up window warning you that you’re about to give your API permission to access a Lambda function. Select OK.

In the new Actions dropdown menu, choose Enable CORS. in the next window, leave the method as POST, and then click the Enable CORS and replace existing CORS headers button.

You should see an alert window asking you to confirm your changes. Select the blue Yes, replace existing values button. The window should look like this:

[insert designwebapp3.jpg]

Deploy API

Now you’re ready to deploy your API. In the Action dropdown menu, choose Deploy API. Select [New Stage] in the Deployment stage dropdown menu. Input dev into the Stage Name field.

Then click the blue Deploy button.

Copy and save the Deploy URL for the next step.

Now you can validate your API.

Ensure the Resources option is selected from the navigation window on the left. Choose POST from the Resources. Then select the blue lightning icon.

In the Request Body window, input the following:

{
    "firstName":"Grace",
    "lastName":"Hopper"
}

Click the blue Test button.

You should see a response like this:

Request: /
Status: 200
Latency: 236 ms
Response Body
{"statusCode": 200, "body": "\"Hello from Lambda, Grace Hopper\""}

Create a Data Table

Now we’re going to create a table using Amazon DynamoDB. We’ll also use the AWS Identity and Access Management (IAM) service to allow your services to interact with one another.

Start by logging into the Amazon DynamoDB console. Click the Create table orange button. Ensure it’s in the same region as your Lambda function, web app, and API.

In the Table name field, input HelloWorldDatabase. In the partition field, input ID.

Leave everything else unchanged. Then click the orange Create table button in the bottom-right corner.

Next, choose HelloWorldDatabase from the list of tables.

In the General Information section, select the Additional info arrow at the borrow of that window. Scroll down to find and then copy the Amazon Resource Number (ARN).

Add IAM Policy to Lambda Function

Now we will authorize your Lambda function to write data to the table you just created.

Navigate back to the AWS Lambda console. Find HelloWorldFunction and open it.

Find the Configuration tab beneath the Function Overview. Select Permissions from the left-hand menu. Find the URL beneath the Role name and double-click, which will open the IAM Management Tool in a new browser tab.

Find the Permissions policies, open the Add permissions dropdown menu, and choose Create inline policy. Then select the JSON tab. Then input the following code:

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

Replace “YOUR-TABLE-ARN” on line 15 with the ARN you saved when you created your table.

Choose the blue Review policy button. In the Name field, input HelloWorldDynamoPolicy and then choose Create policy. You can now close that tab and navigate back to your Lambda function.

Modify Lambda Function to Write to DynamoDB

In the Lambda function, select the Code tab. Then input 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)
    }

As you can see, this Lambda function code imports the AWS SDK as Boto3. It then uses that package to create objects in a dynamoDB.

Test the Lambda Function

Now you’re going to test the Lambda function. Start by clicking the orange Test button. You should see a message reading Execution result: succeeded with a green background.

Now open the dynamoDB console again.

In the left-hand window, find the Explore items section under Tables. Find the HelloWorldDatabase. Look for the Items returned window, where you should see the item Ada Lovelace.

You have now created a Lambda function that will accept an inputted name and add it to a database.

Connect Web App to a Database

Now we’re going to connect all these pieces together. We’ll take the static web page we created using the Amplify console, use that website to deploy an API, and write an entry to the dynamoDB.

Start by opening the index.html you created at the beginning of this exercise. Input the following:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Hello World</title>
    <!-- Add some CSS to change client UI -->
    <style>
    body {
        background-color: #232F3E;
        }
    label, button {
        color: #FF9900;
        font-family: Arial, Helvetica, sans-serif;
        font-size: 20px;
        margin-left: 40px;
        }
     input {
        color: #232F3E;
        font-family: Arial, Helvetica, sans-serif;
        font-size: 20px;
        margin-left: 20px;
        }
    </style>
    <script>
        // define the callAPI function that takes a first name and last name as parameters
        var callAPI = (firstName,lastName)=>{
            // 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({"firstName":firstName,"lastName":lastName});
            // 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("YOUR-API-INVOKE-URL", requestOptions)
            .then(response => response.text())
            .then(result => alert(JSON.parse(result).body))
            .catch(error => console.log('error', error));
        }
    </script>
</head>
<body>
    <form>
        <label>First Name :</label>
        <input type="text" id="fName">
        <label>Last Name :</label>
        <input type="text" id="lName">
        <!-- set button onClick method to call function we defined passing input values as parameters -->
        <button type="button" onclick="callAPI(document.getElementById('fName').value,document.getElementById('lName').value)">Call API</button>
    </form>
</body>
</html>

Make sure to replace “Your-API-Invoke-URL” with the API URL you saved earlier. Save the file and create a .zip file containing just index.html again.

Open the Amplify console again. Open the web app you created earlier.

Drag and drop the ZIP file you just created again. This will begin the deployment process immediately, as well.

Now you’re going to test the web app. Select the URL under Domain. This will open a new browser tab where you will see a form for inputting a first name and last name. Input a name and then click the Call API button.

You should see a message pop up reading “Hello From Lambda” + whatever name you input. When you refresh the DynamoDB website, you should see the name you input as an item in the table.

Final Thoughts on Building a Web App and Connecting It To a Database Using AWS

Once you know what you’re doing, it’s easy to set up a static website, build and deploy an API, and connect both to a database in just a few minutes. Even though it’s simple to set up and implement, it’s still robust enough to make fully functional web apps and databases.

Nothing says you need to stop at just two variables, for instance. You can modify the form on the HTML file to accept whatever inputs you want to document and then easily store them in a table.

Even better, you can style them to your heart’s content using CSS. Once you know what you’re doing, AWS is ideal for creating static websites and customized databases. This can save you hours of headaches trying to become a master frontend and backend developer.