This tutorial shows how to build a serverless API for Page View Counter with Python and Redis. The API will the count page views and show it in JSON format.

The Stack

  • Serverless compute: AWS Lambda (Python)
  • Serverless data store: Redis via Upstash
  • Deployment tool: AWS SAM

Prerequisites:

  • An AWS account for AWS Lambda functions.
  • Install AWS SAM CLI tool as described here to create and deploy the project.
  • An Upstash account for serverless Redis.

Step 1: Init the Project

Run the sam init and then

  • Select AWS Quick Start Templates
  • Select 2 - python3.8
  • Enter your project name: python-redis-example
  • Select 1 - Hello World Example SAM will generate your project in a new folder.

Step 2: Install a Redis Client

Our only dependency is redis client. Install python redis via pip install redis. Also add redis to requirements.txt.

Step 3: Create a Redis Database

Create a Redis database from Upstash console. Free tier should be enough. It is pretty straight forward but if you need help, check getting started guide. In the database details page, click the Connect button. You will need the endpoint and password in the next step.

Step 4: The function Code

Edit the hello-world>app.py as below:

import json
import redis

r = redis.StrictRedis(
host='YOUR_REDIS_ENDPOINT',
port='YOUR_REDIS_PORT',
password='YOUR_REDIS_PASSWORD',
charset="utf-8",
decode_responses=True)

def lambda_handler(event, context):
counter = r.incr('counter')

    return {
        "statusCode": 200,
        "body": json.dumps({
            "counter": counter,
        }),
}

Replace the “YOUR_REDIS_ENDPOINT”, “YOUR_REDIS_PORT” and “YOUR_REDIS_PASSWORD” with your database’s endpoint and password which you created in the Step 3. The code simply increments a counter in Redis database and returns its value in json format.

Step 5: Deployment

Now we are ready to deploy our API. First build it via sam build. Then run the command sam local start-api. You can check your API locally on http://127.0.0.1:3000/hello



If it is working, you can deploy your app to AWS by running sam deploy --guided. Enter a stack name and pick your region. After confirming changes, the deployment should begin. The command will output API Gateway endpoint URL, you can check the API in your browser.



You can also check your deployment on your AWS console. You will see your function has been created. Click on your function, you will see the code is uploaded and API Gateway is configured.

Notes

  • Check the template.yaml file. You can add new functions and APIGateway endpoints editing this file.
  • It is a good practice to keep your Redis endpoint and password as environment variable.
  • You can use serverless framework instead of AWS SAM to deploy your function.