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.
Run the sam init and then
Our only dependency is redis client. Install python redis via
pip install redis
. Also add redis to requirements.txt
.
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.
Edit the hello-world>app.py
as below:
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.
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.