Source code available at: GitHub Repository
In this section, we will implement a visitor count tracking system using AWS API Gateway, Lambda, and DynamoDB.
Architecture
Introduction
In this section, we will implement a visitor count tracking system using AWS API Gateway, Lambda, and DynamoDB.
Step 1: Set Up DynamoDB Table
- Open the AWS Management Console.
- Navigate to DynamoDB.
- Create a new table named
visitorcounts
. - Set the primary key as
id
with typeString
. - Add an initial item with
id
set to0
andviews
set to0
.
Step 2: Create a Lambda Function
- Open the AWS Management Console.
- Navigate to Lambda.
- Create a new Lambda function named
VisitorCountFunction
. - Set the runtime to Python 3.x.
- Use the code from
lambda.py
for the Lambda function. - Configure the Lambda function with an execution role that has access to DynamoDB.
Step 3: Set Up API Gateway
-
Open the AWS Management Console.
-
Navigate to API Gateway.
-
Create a new API.
-
Create a new resource named
visitors
. -
Create a new GET method for the
visitors
resource. -
Integrate the GET method with the Lambda function
VisitorCountFunction
. -
Enable CORS for the GET method.
-
Add a mapping template for the GET method to pass query string parameters to the Lambda function:
{ "queryStringParameters": { "count": "$input.params('count')" } }
-
Deploy the API to a stage (e.g.,
prod
).
Step 4: Implement Client-Side Code
-
Add the code from
visitorcount.js
to your website to track unique visitors. -
Ensure you have an HTML element with
id="visitors"
where the count will be displayed:<div id="visitors"></div>
Step 5: Test the Implementation
- Open your website in a browser.
- Verify that the visitor count is displayed and increments for unique visitors.
- Check that the count does not increment for returning visitors.