Building a Serverless Feedback Web Application with AWS Lambda, API Gateway, and DynamoDB

Introduction

Serverless architectures have become increasingly popular due to their scalability, cost-effectiveness, and simplicity. In this blog post, we will go over building a serverless feedback web application using AWS Lambda, API Gateway, and DynamoDB. This example will demonstrate how an HTTP request from the frontend triggers a Lambda function through API Gateway, which then writes data to a DynamoDB table.

Overview of the Application

Our serverless feedback web application will consist of a simple HTML form where users can submit their name, email, and feedback message. When the form is submitted, the frontend sends an HTTP POST request to an API Gateway endpoint, which triggers a Lambda function to process the user feedback data and write it to a DynamoDB table.

We will divide our walkthrough into four sections: Frontend, API Gateway, AWS Lambda, and DynamoDB.

Frontend

The frontend of our web application consists of an HTML form with input fields for the user's name, email, and feedback message. We'll use JavaScript to send an HTTP POST request to our API Gateway endpoint when the form is submitted.

To host the frontend, you can use a static website hosting service like Amazon S3 or a content delivery network like Amazon CloudFront. This allows you to host your HTML, CSS, and JavaScript files efficiently and ensures fast delivery to users.

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Feedback</title>
</head>
<body>
    <h1>User Feedback</h1>
    <form id="feedbackForm">
        <label for="name">Name:</label>
        <input type="text" id="name" required><br><br>

        <label for="email">Email:</label>
        <input type="email" id="email" required><br><br>

        <label for="message">Message:</label>
        <textarea id="message" required></textarea><br><br>

        <button type="submit">Submit</button>
    </form>

    <script>
        const form = document.getElementById("feedbackForm");
        form.addEventListener("submit", async (e) => {
            e.preventDefault();

            const data = {
                name: document.getElementById("name").value,
                email: document.getElementById("email").value,
                message: document.getElementById("message").value
            };

            const apiGatewayUrl = "https://your-api-gateway-url/submitFeedback";

            const response = await fetch(apiGatewayUrl, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(data)
            });

            if (response.ok) {
                alert("Feedback submitted successfully!");
                form.reset();
            } else {
                alert("An error occurred while submitting your feedback. Please try again.");
            }
        });
    </script>
</body>
</html>

API Gateway

API Gateway serves as the entry point for your application's backend, managing incoming HTTP requests and routing them to the appropriate Lambda function. To set up API Gateway for our feedback web application, follow these steps:

  1. Create a new REST API in the API Gateway service.
  2. Add a new resource (e.g., /submitFeedback).
  3. Add a POST method for this resource.
  4. Choose "Lambda Function" as the integration type and select the AWS Lambda function you will create in the next section.
  5. Deploy your API to a stage, and note the Invoke URL, which will be used as apiGatewayUrl in the frontend JavaScript code.

AWS Lambda

We will create a new Lambda function to process the user feedback data and write it to a DynamoDB table. This function will be triggered by the API Gateway POST method. Follow these steps to set up the Lambda function:

  1. Create a new function (e.g., submitFeedbackFunction) in the Lambda service.
  2. Choose a runtime, such as Node.js or Python, and create the function.
  3. Add the Lambda function code, which processes the user feedback data and writes it to a DynamoDB table.
  4. Provide your Lambda function with the required permissions to access DynamoDB (e.g., by attaching an IAM role with the AmazonDynamoDBFullAccess policy).
const AWS = require("aws-sdk");
const dynamo = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event) => {
    const data = JSON.parse(event.body);

    const params = {
        TableName: "UserFeedback",
        Item: {
            id: new Date().getTime().toString(),
            name: data.name,
            email: data.email,
            message: data.message,
            timestamp: new Date().toISOString()
        }
    };

    try {
        await dynamo.put(params).promise();
        return {
            statusCode: 200,
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ message: "Feedback submitted successfully." })
        };
    } catch (error) {
        console.error("An error occurred while submitting feedback:", error);
        return {
            statusCode: 500,
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ message: "An error occurred while submitting feedback." })
        };
    }
};

DynamoDB

Finally, we will create a new DynamoDB table to store the user feedback data. To set up the DynamoDB table, follow these steps:

  1. Create a new table (e.g., "UserFeedback") in the DynamoDB service.
  2. Set the primary key to "id" (String).
  3. Configure the table's settings, such as read/write capacity or auto-scaling, based on your requirements.

Conclusion

By using serverless architectures on AWS, you can build scalable, cost-effective, and easy-to-manage web applications without the need to maintain servers.
This feedback application is just one example of the many use cases for serverless architectures. Whether you're building web applications, processing large amounts of data, or creating complex workflows, serverless architectures on AWS can help you achieve your goals with minimal overhead and maximum efficiency.