Building a Serverless Web App on AWS using DynamoDB and API Gateway

author

Vishaal

October 25, 2023

Last updated: October 27, 2023

Guide to Building a serverless web app on AWS

What is a serverless web app?

If you are interested in building a web app without worrying about servers, scalability, or maintenance, then you might want to consider building a serverless web app on AWS. It is a web application that runs on the cloud without requiring any servers to host or manage it. Instead, it relies on serverless computing services, such as AWS Lambda, to execute the backend logic and interact with other cloud resources.

Why should you use AWS Lambda?

AWS Lambda is a service that lets you run code without provisioning or managing servers. With Lambda, you can run code for virtually any type of application or backend service. You can also use Lambda to integrate with other AWS services, such as Amazon S3, Amazon DynamoDB, Amazon API Gateway, and more.

In this blog, I will show you how to build a serverless web app on AWS services using AWS Lambda as the core component. You will be able to create a simple web page that allows users to enter their name and email address, and store them in a DynamoDB table.

We will also use API Gateway to create an endpoint that invokes the Lambda function and returns the data to the web page. By the end of this blog, you will have a basic understanding of AWS serverless web app architecture and how to build a serverless web application in AWS.

Let’s get started with the steps to building a serverless web app on AWS.

What do you need to get started to build a serverless web app?

Before getting started with the project, I will list out the prerequisites that you will need to start building your first serverless web app.

  • A basic knowledge of HTML, CSS, and JavaScript as you will be using these languages to create the front end of your web app. 
  • A basic knowledge of Python so that you can write the Lambda function that handles the backend logic of your web app. 
  • An AWS account to access and use the AWS services that we will use in this project.
  • The AWS Command Line Interface to interact with the AWS services from your terminal. If you don’t have one you can install and configure it with these instructions
  • A code editor of your choice. I would recommend Visual Studio Code, Atom, Sublime Text, etc. 

Getting started with Building a Serverless Web App with AWS Lambda

Getting started with building your serverless web app with AWS lambda

Step 1: Create an AWS account and configure the AWS CLI

In order to start building a serverless web app on AWS you should first create an AWS account and configure the AWS CLI. This will allow you to access and use the AWS services that we will need for this project. I would suggest you to follow these steps: 

  • Go to the AWS homepage and click on the Create button to get started.
  • Enter your official details wherever necessary.
  • Choose the Personal or Professional account type, depending on your preference. 
  • Enter your payment information. You will need a valid credit card or debit card to create an AWS account. (Don’t worry, you will not be charged unless you exceed the free tier limits of the AWS services that you use)
  • Verify your identity by entering a code that will be sent to your phone number or email address.
  • Choose a plan that suits your requirements to proceed further. I would suggest you go through each of them to learn more about the features and benefits, such as technical support, faster response times, and more.
  • Once you complete the sign-up process you will see a confirmation page that welcomes you to AWS.

Now that you have created an account, proceed further to configure the AWS CLI. 

  • Install the AWS CLI on your computer by downloading it from the official website. Follow the on-screen instructions for your operating system to complete the installation.
  • Open a terminal window (CMD or PowerShell) and run the command aws configure. You will be prompted to enter your AWS Access Key ID and AWS Secret Access Key, which are credentials that allow you to access and use the AWS services that you can find in your AWS console
  • You should also enter your AWS Region and Output Format as it will affect how the AWS CLI interacts with the AWS services. (If your region isn’t listed on the website, you can choose the one that is close to your location)
  • Test your configuration by running the command aws s3 ls. This command lists all the S3 buckets in your account. 
  • If you see a list of buckets or an empty output, then your configuration is successful. However, if you see an error message, then you need to check your configuration and try again.

Step 2: Create a simple HTML page and upload it to S3

The next step in building a serverless web app on AWS is to create a simple HTML page that will serve as the front end of your web app. You will be using HTML, CSS, and JavaScript to create a web page that allows users to enter their basic information and displays a message when they submit the form. You will also upload the HTML page to S3, which is a service that provides secure, durable, and scalable object storage.

Now you can proceed to create your first serverless web app:

  • Open your code editor and create a new file named index.html.
  • Copy and paste the following code into the file: 

<html>

<head>

    <style>

        body {

            font-family: Arial, sans-serif;

            text-align: center;

        }

        h1 {

            color: blue;

        }

        form {

            margin: 20px auto;

            width: 300px;

        }

        input {

            display: block;

            margin: 10px auto;

        }

        button {

            background-color: green;

            color: white;

            padding: 10px 20px;

            border: none;

            cursor: pointer;

        }

        #message {

            display: none;

            color: red;

        }

    </style>

</head>

<body>

    <h1>Serverless Web App Demo</h1>

    <form id=”form”>

        <input type=”text” id=”name” placeholder=”Enter your name” required>

        <input type=”email” id=”email address” placeholder=”Enter your email” required>

        <button type=”submit”>Submit</button>

    </form>

    <p id=”message”>Thank you for submitting your details!</p>

    <script>

        // Get the form element

        var form = document.getElementById(“form”);

        // Add an event listener to handle the form submission

        form.addEventListener(“submit”, function(event) {

            // Prevent the default form submission behavior

            event.preventDefault();

            // Get the name and email values from the input elements

            var name = document.getElementById(“name”).value;

            var email = document.getElementById(“email address”).value;

            // Call the sendData function to send the data to the backend

            sendData(name, email address);

            // Show the message element

            document.getElementById(“message”).style.display = “block”;

            // Clear the input values

            document.getElementById(“name”).value = “”;

            document.getElementById(“email address”).value = “”;

        });

        // Define a function to send the data to the backend

        function sendData(name, email) {

            // Create an XMLHttpRequest object

            var xhr = new XMLHttpRequest();

            // Set the request method, URL, and asynchronous flag

            xhr.open(“POST”, “https://your-api-gateway-url”, true);

            // Set the request header for the content type

            xhr.setRequestHeader(“Content-Type”, “application/json”);

            // Define a callback function to handle the response

            xhr.onreadystatechange = function() {

                // Check if the request is completed

                if (xhr.readyState == 4) {

                    // Check if the status is OK

                    if (xhr.status == 200) {

                        // Parse the response as JSON

                        var response = JSON.parse(xhr.responseText);

                        // Log the response to the console

                        console.log(response);

                    } else {

                        // Log the error to the console

                        console.error(xhr.statusText);

                    }

                }

            };

            // Create a data object with the name and email properties

            var data = {

                name: name,

                email: email address

            };

            // Send the data as JSON string

            xhr.send(JSON.stringify(data));

        }

    </script>

</body>

</html>

Step 3: Write a Lambda function to handle user input and store it in a Dynamic DB

To proceed with building a serverless web app on AWS, you should write a Lambda function that will handle the user input and store it in DynamoDB. DynamoDB is a service that provides a fast and flexible NoSQL database. You can use DynamoDB to store the name and email address of the users who submit the form on your web page.

To write a Lambda function, follow these steps:

  • Go to your AWS console and click on Lambda under Compute.
  • Click on the Create function and choose Author from scratch.
  • Enter a name for your function. You can use any name that you like, such as serverless-web-app-demo. 
  • Choose Python 3.8 as the runtime. 
  • Choose Create a new role with basic Lambda permissions as the execution role. 
  • Click on the Create function. 
  • In the code editor, delete the default code and copy and paste the following code: 

import json

import boto3

# Create a DynamoDB resource

dynamodb = boto3.resource(‘dynamodb’)

# Get the table object

table = dynamodb.Table(‘serverless-web-app-demo’)

# Define a handler function

def lambda_handler(event, context):

    # Get the name and email from the event body

    name = event[‘name’]

    email address’= event[’email’]

    # Put the item into the table

    table.put_item(

        Item={

            ‘name’: name,

            ’email address’: email

        }

    )

    # Return a response with status code 200 and a message

    return {

        ‘statusCode’: 200,

        ‘body’: json.dumps(‘Data saved successfully!’)

    }

import json

import boto3

# Create a DynamoDB resource

dynamodb = boto3.resource(‘dynamodb’)

# Get the table object

table = dynamodb.Table(‘serverless-web-app-demo’)

# Define a handler function

def lambda_handler(event, context):

    # Get the name and email from the event body

    name = event[‘name’]

    email address’= event[’email’]

    # Put the item into the table

    table.put_item(

        Item={

            ‘name’: name,

            ’email address’: email

        }

    )

    # Return a response with status code 200 and a message

    return {

        ‘statusCode’: 200,

        ‘body’: json.dumps(‘Data saved successfully!’)

    }

import json

import boto3

# Create a DynamoDB resource

dynamodb = boto3.resource(‘dynamodb’)

# Get the table object

table = dynamodb.Table(‘serverless-web-app-demo’)

# Define a handler function

def lambda_handler(event, context):

    # Get the name and email from the event body

    name = event[‘name’]

    email address’= event[’email’]

    # Put the item into the table

    table.put_item(

        Item={

            ‘name’: name,

            ’email address’: email

        }

    )

    # Return a response with status code 200 and a message

    return {

        ‘statusCode’: 200,

        ‘body’: json.dumps(‘Data saved successfully!’)

    }

  • Now save your file to ensure that you don’t lose your progress 

Now that you have successfully created your Lambda function, it’s time to test it.
Click on Test and choose Configure test events.
Enter a name for your test event. You can use any name that you like, such as test-event.
In the event template, delete the default JSON and copy and paste the following JSON:

{
“name”: “Vishaal”,
“email address”: “vishaal@example.com”
}

  • Click on Create.
  • Click on Test again and see the result. You should see a green banner that says Execution result: “Succeeded” and a response body that says “Data saved successfully!”.
  • Go to your AWS console and click on DynamoDB under Database.
  • Click on Tables and then click on serverless-web-app-demo.
  • Click on Items and see the item that you just inserted. You should see an item with the name Vishaal and email address as vishaal@example.com.

Step 4: Create an API Gateway endpoint to invoke the Lambda function

The final step in building a serverless web app on AWS is to create an API Gateway endpoint that invokes the Lambda function. API Gateway is a service that lets you create, manage, and secure APIs for your applications. You will have to use API Gateway to create a RESTful API that connects your web page to your Lambda function.

To create an API Gateway endpoint, follow these steps:

  • Go to your AWS console and click on API Gateway under Networking & Content Delivery.
  • Click on Create API and choose REST API.
  • Enter a name for your API. (You can use any random name)
  • Choose Regional as the endpoint type and click on Create API.
  • Click on Actions and then go to Create Resource.
  • Enter a name for your resource. You can use any name that you like, such as data.
  • Check the Enable API Gateway CORS option. (This will allow your web page to make cross-origin requests to your API)
  • Click on Create Resource.
  • Click on the name of your resource and then click on Actions to Create Method.
  • Choose POST as the HTTP method and click on the checkmark icon.
  • Choose Lambda Function as the integration type and check the Use Lambda Proxy integration option (This will pass the request data directly to your Lambda function)
  • Choose the same region as your Lambda function and enter the name of your Lambda function in the Lambda Function field (For example, serverless-web-app-demo)
  • Click on Save and confirm the permission to add a trigger to your Lambda function.
  • Click on Actions and then Deploy API. 
  • Choose New Stage as the deployment stage and enter a name for your stage (You can use any name that you like, such as prod)
  • Click on Deploy.
  • Copy the URL of your API from the top of the page (You can use this URL to invoke your Lambda function from your web page)

Step 5: Modify the HTML page to send and receive data from the API Gateway

The last step to building a serverless web app on AWS is to modify the HTML page to send and receive data from the API Gateway. You will use JavaScript to make an AJAX request to your API Gateway endpoint and display the response on your web page. 

To modify the HTML page, follow these steps:

  • Open your code editor and open your index.html file. 
  • Locate the line that says xhr.open (“POST”, “https://your-api-gateway-url”, true) 
  • Replace the URL with that of your API Gateway endpoint that you copied in the previous section. (It will be something like https://abc123.execute-api.us-east-1.amazonaws.com/prod/data) 
  • Save the file. 
  • Go to your AWS console and click on S3 under Storage. 
  • Click on the name of your bucket and then click on Upload. 
  • Click on Add files and select your index.html file from your computer.
  • Click on Upload.

Step 6: Test and deploy the serverless web app

After building a serverless web app on AWS, we can proceed with testing and deploying it. You can use your browser to access the web page to see how it works. 

  • Open your browser and paste the URL of your HTML page that you copied earlier. (This should bring up your webpage) 
  • Enter your name and email address in the input fields and click on Submit. 
  • Now you should see a message that says “Thank you for submitting your details!” and a console log that shows the response from your Lambda function. 
  • You can also open the console by pressing Ctrl+Shift+I on Windows or Cmd+Option+I on Mac and clicking on the Console tab. 
  • Go to your AWS console and click on DynamoDB under Database. 
  • Click on Tables and then click on the demo. 
  • Click on Items. (Now you should be able to see an item with your name and email address as the values) 

Now that you have tested the serverless web app and verified that it works as expected, you can proceed to deploy it.
There is no additional step required to deploy the serverless web app. You can directly share this URL with anyone who wants to use your web app.
In case if you want to use a custom domain name for your web app you will need to register a domain name with a domain registrar.

How to make changes to a serverless web application built with AWS lambda?

In case you change your mind and want to make any changes to it, here’s how you can do it.

  • If you want to make any changes to your web page, such as changing the layout, style, or functionality, you can edit your index.html file in your code editor and upload it to S3 again. 
  • If you want to change your Lambda function, such as changing the logic, parameters, or output, you can edit your code in the AWS console or use the AWS CLI to update your function.
  • If you want to make any changes to your API Gateway endpoint, such as changing the method, resource, or integration, you can edit your settings in the AWS console and deploy your API again.
  • If you change your mind and want to delete it, go to your AWS console and click on S3 under Storage to delete your S3 bucket. Click on the name of your bucket and then click on Empty. Confirm that you want to delete all the objects in your bucket. Then click on Delete and confirm that you want to delete your bucket. 
  • To delete the Lambda function, click on Lambda under Compute in your console. Click on the name of your function, and then proceed to Actions and then Delete. (Click confirm in the prompt on your screen to proceed)

Conclusion

Now that you can build a serverless web app on AWS on your own, you can scale it up easily. By using AWS Lambda, DynamoDB, and API Gateway you can build reliable, and cost-effective web applications without managing any servers.

Related Articles

field image

Stuck in the Insurance Stone Age? Discover the Power of Portal Software in 2024 Remember those rolodexes and fax machines? Yeah, the insurance industry can feel a bit like that sometimes. But what if you could ditch the outdated tools and access a war room of information – all online and at your fingertips? Here’s […]

author-image

Calibraint

Author

26 Apr 2024

field image

Forget “For Sale” signs outside houses and endless cold calls. The future of real estate lead generation is undeniably digital. In today’s world, potential buyers begin their home search online, making a wide web presence crucial for any agent looking to maximize property sales.  In this blog post, we will explore how these innovative tools […]

author-image

Calibraint

Author

04 Apr 2024

field image

An Introduction To Cost Reduction In Inventory Management Do you ever feel like you’re constantly playing inventory whack-a-mole? Stockouts costing you sales? Or maybe you’re drowning in a sea of unused products eating away at your profits? Inefficient inventory management can be a major drain on your business resources. But what if there was a […]

author-image

Haritha

29 Mar 2024

field image

What If I Told You That A Website Is Already An App? There is a saying “If you can’t convince them, confuse them”! This is exactly what Web Apps and Mobile Apps do with us. So if “Web App vs Mobile App: Which one should I choose” is your question, then this blog has all […]

author-image

Calibraint

Author

13 Feb 2024

field image

PWAs are no longer a futuristic fantasy; they’re a present-day reality, transforming how businesses connect with their audience. Stats back this up as several reports suggest increased conversions and user engagement with PWAs over traditional websites. And let’s not forget the search engine love – PWAs get indexed and appear in app store listings, expanding […]

author-image

Calibraint

Author

10 Feb 2024

field image

WE HAVE DETECTED AN UNSAFE LINK!!!! Ever felt that gut-wrenching ‘ohhh noo’ moment when you realize your website is under attack? In 2024, the web is a wild west of cyber threats, and your website might be the next frontier.  Picture this: Everything you’ve built vanished in the blink of a malicious code. But fear […]

author-image

Haritha

25 Jan 2024

Let's Start A Conversation

Table of Contents