Introduction: Project Overview and Prerequisites

Building and deploying serverless applications is becoming increasingly popular in today’s cloud-first world. This guide will walk you through creating and deploying a fully functional serverless web calculator on AWS, using services like AWS Amplify, AWS Lambda, Amazon API Gateway, and AWS DynamoDB. By the end of this tutorial, you’ll have a working calculator that performs basic math operations, stores results, and can be easily extended with additional features.

Prerequisites:

  • AWS account
  • Basic knowledge of AWS services (Amplify, Lambda, API Gateway, DynamoDB)
  • Familiarity with Python and JavaScript
  • AWS CLI installed and configured
  • Basic understanding of HTML/CSS/JavaScript

Creating the Frontend: Designing and Deploying the Calculator Interface with AWS Amplify

The first step in our project is to design and deploy the calculator interface using AWS Amplify. Amplify simplifies web application deployment by automating the setup of hosting environments, CI/CD pipelines, and more.

Steps:

  1. Initialize Amplify Project:
    • Use the AWS Amplify CLI to initialize a new project in your local development environment.


amplify init

  • Follow the prompts to configure your project, selecting the appropriate settings for your application.
  1. Build the Calculator Interface:
    • Create a simple HTML/CSS/JavaScript interface for the calculator. The interface should include buttons for numbers and basic operations (addition, subtraction, multiplication, division) and a display area to show results.

<div id=”calculator”>

    <input type=”text” id=”result” readonly>

    <div id=”buttons”>

        <!– Number and operator buttons go here –>

    </div>

</div>

<script src=”app.js”></script>

  1. Deploy the Frontend:
    • Deploy the calculator interface using Amplify’s hosting feature.


amplify hosting add

amplify publish

  • Your calculator frontend is now live and hosted on AWS.

Implementing Calculation Logic: Building a Serverless Python Lambda Function for Math Operations

With the front end ready, the next step is creating a backend service that handles the calculations. We’ll use AWS Lambda to create a serverless function that performs these operations.

Steps:

  1. Create Lambda Function:
    • In the AWS Management Console, navigate to the Lambda service and create a new function. Choose Python as the runtime.
    • Write the Python code to handle basic math operations.


import json

def lambda_handler(event, context):

    operation = event[‘operation’]

    num1 = float(event[‘num1’])

    num2 = float(event[‘num2’])

    

    if operation == ‘add’:

        result = num1 + num2

    elif operation == ‘subtract’:

        result = num1 – num2

    elif operation == ‘multiply’:

        result = num1 * num2

    elif operation == ‘divide’:

        result = num1 / num2

    else:

        return {“statusCode”: 400, “body”: json.dumps(“Invalid operation”)}

    

    return {“statusCode”: 200, “body”: json.dumps(result)}

  1. Deploy the Lambda Function:
    • Deploy the function and note its ARN, which will be needed for API Gateway integration.

API Gateway Integration: Setting Up a REST API to Connect the Frontend and Backend

We’ll set up an Amazon API Gateway API to connect the frontend calculator with the Lambda function. This will allow the front end to send requests to the back end for calculations.

Steps:

  1. Create a New API:
    • In the API Gateway console, create a new REST API.
    • Define methods (e.g., POST) for the API, linking them to the corresponding Lambda function created earlier.
  2. Deploy the API:
    • Deploy the API to a stage (e.g., “prod”) and obtain the invoke URL. The frontend will use this URL to make requests.
  3. Integrate Frontend with API:
    • Update the frontend JavaScript code to make API calls using the fetch API or Axios to the API Gateway endpoint.


function calculate(operation, num1, num2) {

    const url = ‘YOUR_API_GATEWAY_INVOKE_URL’;

    fetch(url, {

        method: ‘POST’,

        headers: {

            ‘Content-Type’: ‘application/json’

        },

        body: JSON.stringify({ operation, num1, num2 })

    })

    .then(response => response.json())

    .then(data => {

        document.getElementById(‘result’).value = data;

    });

}

Data Persistence: Storing Calculation Results with AWS DynamoDB

We will store the calculation results in a DynamoDB table to add a persistence layer. This allows us to retrieve and display past calculations if needed.

Steps:

  1. Create DynamoDB Table:
    • In the DynamoDB console, create a new table to store calculation results. Define the necessary attributes (e.g., operation, num1, num2, result).
  2. Update Lambda Function:
    • Modify the Lambda function to save the calculation result to DynamoDB.


import boto3

dynamodb = boto3.resource(‘dynamodb’)

table = dynamodb.Table(‘CalculatorResults’)

def lambda_handler(event, context):

    # existing logic…

    table.put_item(Item={

        ‘operation’: operation,

        ‘num1’: str(num1),

        ‘num2’: str(num2),

        ‘result’: str(result)

    })

    return {“statusCode”: 200, “body”: json.dumps(result)}

Conclusion: Project Recap and Future Development Possibilities

In this guide, we’ve built and deployed a serverless web calculator on AWS, utilizing services like AWS Amplify, Lambda, API Gateway, and DynamoDB. This calculator performs basic math operations and persists the results in DynamoDB.

Future Development Possibilities:

  • Enhance the calculator with additional operations (e.g., square roots, exponents).
  • Implement user authentication to track individual calculation histories.
  • Build a more sophisticated frontend with a framework like React or Angular.
  • Add error handling and validation for more robust user interaction.

References

Serverless Web Application

Build a Basic Web Application