Build Your First AWS Project: Serverless Calculator App Using CloudFormation


Looking to kickstart your journey into serverless development with AWS? This hands-on guide walks you through building a serverless calculator app using AWS CloudFormation. You’ll use services like AWS Lambda, API Gateway, and S3 to build and deploy a fully functional calculator that requires no backend server management.


Why Build a Serverless Calculator App?

A calculator may sound simple, but it’s a perfect starting point to understand:

  • Function-as-a-Service (FaaS) using AWS Lambda

  • Infrastructure as Code (IaC) using AWS CloudFormation

  • API integration via Amazon API Gateway

  • Hosting with Amazon S3

  • Event-driven programming on AWS

By the end of this tutorial, you’ll have learned how to use CloudFormation templates to spin up a complete serverless stack.


Project Architecture Overview

Your calculator app will consist of the following components:

  • Amazon S3: To host the static frontend

  • API Gateway: To expose REST endpoints (e.g., /add, /subtract)

  • AWS Lambda Functions: For computing results based on input

  • AWS CloudFormation: For provisioning infrastructure automatically


Step 1: Set Up Your CloudFormation Template

Create a file called calculator-template.yaml and define the resources:


AWSTemplateFormatVersion: '2010-09-09'

Resources:

  AddFunction:

    Type: AWS::Lambda::Function

    Properties:

      FunctionName: AddFunction

      Handler: index. add

      Role: !GetAtt LambdaExecutionRole.Arn

      Code:

        ZipFile: |

          def add(event, context):

              a = int(event['queryStringParameters']['a'])

              b = int(event['queryStringParameters']['b'])

              return {

                  'statusCode': 200,

                  'body': str(a + b)

              }

      Runtime: python3.9


  LambdaExecutionRole:

    Type: AWS::IAM::Role

    Properties:

      RoleName: CalculatorLambdaExecutionRole

      AssumeRolePolicyDocument:

        Version: '2012-10-17'

        Statement:

          - Effect: Allow

            Principal:

              Service: lambda.amazonaws.com

            Action: sts:AssumeRole

      Policies:

        - PolicyName: LambdaBasicExecution

          PolicyDocument:

            Version: '2012-10-17'

            Statement:

              - Effect: Allow

                Action:

                  - logs:CreateLogGroup

                  - logs:CreateLogStream

                  - logs:PutLogEvents

                Resource: "*"


Similarly, you can extend this template for subtraction, multiplication, and division functions.


Step 2: Set Up API Gateway Integration

Add an AWS::ApiGateway::RestApi and link it to your Lambda functions using:

  • AWS::ApiGateway::Resource

  • AWS::ApiGateway::Method

  • AWS::Lambda::Permission

Example:


CalculatorApi:

  Type: AWS::ApiGateway::RestApi

  Properties:

    Name: CalculatorAPI


This exposes endpoints like GET /add?a=10&b=5.


Step 3: Host the Frontend on S3

Create a simple HTML/JS frontend and upload it to an S3 bucket:


<form>

  <input type="number" id="a" />

  <input type="number" id="b" />

  <button onclick="calculate()">Add</button>

</form>


<script>

function calculate() {

  const a = document.getElementById("a").value;

  const b = document.getElementById("b").value;

  fetch(`https://<your-api-endpoint>/add?a=${a}&b=${b}`)

    .then(res => res.text())

    .then(result => alert("Result: " + result));

}

</script>


Enable static website hosting on the S3 bucket and make it public (or use CloudFront with signed URLs for secure access).


Step 4: Deploy the CloudFormation Stack

Use the AWS CLI or Management Console:


aws cloudformation deploy \

  --template-file calculator-template.yaml \

  --stack-name ServerlessCalculatorApp \

  --capabilities CAPABILITY_NAMED_IAM


Once deployed, note the API endpoint and S3 static site URL to test the app.


Step 5: Test Your Calculator

Try different operations:

  • GET /add?a=10&b=5

  • GET /subtract?a=20&b=6

  • Extend your Lambda functions and API methods for multiplication and division.


Bonus: Add CI/CD with CodePipeline

For bonus points, integrate your CloudFormation deployment into a pipeline using AWS CodePipeline or GitHub Actions to automate your stack updates.


Conclusion

Congratulations! You've just built your first serverless calculator app on AWS using CloudFormation. This simple project gives you a practical foundation in using AWS serverless tools, Infrastructure as Code, and RESTful APIs.

Comments

Popular posts from this blog

HTTP Basic vs API Key Auth: Best Practices for Secure API Development

ECS Deployment Best Practices: Blue/Green with CodePipeline and CodeDeploy

Deploying Next.js Apps on AWS: A Complete Step-by-Step Guide

YouTube Channel