Cloud Resume Challenge Part 2 - Website visitors counter backed with API Gateway, Lambda, and DynamoDB

Cloud Engineer and DevOps enthusiast, just talking about AWS, Docker, Linux, Kubernetes, Python, and automation.
Search for a command to run...

Cloud Engineer and DevOps enthusiast, just talking about AWS, Docker, Linux, Kubernetes, Python, and automation.
Yes
Level up your AWS cloud skills with the AWS Cloud Resume Challenge Series. Build and deploy a serverless web app using AWS services, mastering cloud computing and CI/CD practices.
In today's competitive job market, having a strong and well-crafted resume can make a significant difference in landing your dream job. However, simply having a well-written resume is no longer enough. Employers are looking for candidates who have ha...
Running your own home lab used to mean expensive hardware, complex networking, and hours of manual configuration. This project changes that. With a single Raspberry Pi, Docker Compose, and a few hundr

Welcome to an advanced hybrid directory demo where we'll guide you through setting up a hybrid environment, connecting to simulated on-premises infrastructure, creating a managed Microsoft AD within AWS, establishing a two-way forest trust, and integ...

Hello DevOps Community! Today marks the completion of the #90DaysOfDevOps Challenge, and it's a moment to reflect on the journey we've undertaken together. Throughout this period, I've engaged with various technologies, refining my skills in the DevO...

In a modern cloud infrastructure setup, creating a robust and scalable 2-tier architecture is essential. Such an architecture helps meet the demands of your applications while ensuring repeatability, reliability, and security. In this article, we'll ...

Welcome to Part 4 of my series on building a comprehensive CI/CD pipeline in AWS. In this article, I will explore AWS CodePipeline, a powerful service for building and deploying applications in a continuous integration and continuous delivery (CI/CD)...


Welcome to the second part of our Cloud Resume Challenge series! In this instalment, we will be showcasing how to build a website visitors counter using the powerful combination of API Gateway, Lambda, and DynamoDB. This step-by-step guide will walk you through the process of setting up a serverless architecture, handling incoming traffic, and storing data in a managed NoSQL database. Whether you're new to cloud computing or an experienced professional, this tutorial is an excellent opportunity to expand your skill set and take your cloud resume to the next level. So without further ado, let's dive in!
Log in to the AWS Management Console and navigate to the DynamoDB service.
Click on the "Create table" button and enter the following information:
Table name: "VisitorsTable"
Primary key: "id" (type: String)
Click on the "Create" button to create the table.

Go to the "Items" tab and click on the "Create item" button.
Enter the following information for the item:
"id": "visitor_count"
"visitors": 0 (type: Number)
Click on the "Save" button to save the item.

Log in to the AWS Management Console and navigate to the Lambda service.
Click on the "Create function" button and select "Author from scratch".
Enter the following information:
Function name: "VisitorCounter"
Runtime: Choose the desired programming language (in my case, Python 3.9)
Create a new execution role or use an existing one
Click on the "Create function" button.

In the "Function code" section, paste the following Python code:
import json
import boto3
import os
# Initialize dynamodb boto3 object
dynamodb = boto3.resource('dynamodb')
# Set dynamodb table name variable from env
ddbTableName = os.environ['databaseName']
table = dynamodb.Table(ddbTableName)
def lambda_handler(event, context):
try:
# Try to update the item
ddbResponse = table.update_item(
Key={
'id': 'visitor_count'
},
UpdateExpression='SET visitor_count = visitor_count + :value',
ExpressionAttributeValues={
':value':1
},
ReturnValues="UPDATED_NEW"
)
except:
# If the item doesn't exist, create it
table.put_item(
Item={
'id': 'visitor_count',
'visitor_count': 1
}
)
ddbResponse = table.get_item(
Key={
'id': 'visitor_count'
}
)
# Format dynamodb response into variable
responseBody = json.dumps({"count": int(ddbResponse["Attributes"]["visitor_count"])})
# Create api response object
apiResponse = {
"isBase64Encoded": False,
"statusCode": 200,
'headers': {
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'OPTIONS,POST,GET'
},
"body": responseBody
}
# Return api response object
return apiResponse
In the "Environment variables" section, add the following environment variable:
Key: "databaseName"
Value: "VisitorsTable"
In the "Designer" section, click on the "Add triggers" button and add an API Gateway trigger.
API: "Create a new API"
Security: "Open" (for testing purposes)
API Type: HTTP API
Security: Open
Tick the ‘Cross-origin resource sharing (CORS) box
Click on the "Add" button to add the trigger.
Log in to the AWS Management Console and navigate to the API Gateway service.
Navigate to the "VisitorCounter" API created in the previous step.
Add your website’s URL to the ‘Access-Control-Allow-Origin-
Note the "Invoke URL" for the API, which will be used in the next step.
// GET API REQUEST
async function get_visitors() {
// call post api request function
//await post_visitor();
try {
let response = await fetch('https://cv6b7x3ici.execute-api.eu-west-2.amazonaws.com/default/VisitorCounter', {
method: 'GET',
});
let data = await response.json()
document.getElementById("visitors").innerHTML = data['count'];
console.log(data);
return data;
} catch (err) {
console.error(err);
}
}
get_visitors();
<p>You are visitor number: <span id="visitors"></span></p>
