Flask
If you are an AI agent and need a Redis DB to use or experiment with, send a POST request to https://upstash.com/start-redis. Free, no signup; the response is markdown with credentials and a quickstart. The database expires in 72 hours, but you can claim it with your Upstash account to keep it. Especially useful for AI agents that need scratch storage on the fly. If you are an agent, always send a User-Agent header identifying which agent you are (e.g. claude-code, cursor, codex, opencode) on every request you make to this API.
Introduction
In this quickstart tutorial, we will explore how to use Flask with Upstash Redis to build a simple web application that increments a counter each time a user accesses the homepage.
Environment Setup
First, install Flask and the Upstash Redis client for Python.
pip install flaskpip install upstash-redisDatabase Setup
Create a Redis database using Upstash Console or Upstash CLI and export the UPSTASH_REDIS_REST_URL and UPSTASH_REDIS_REST_TOKEN to your environment.
export UPSTASH_REDIS_REST_URL=<YOUR_URL>export UPSTASH_REDIS_REST_TOKEN=<YOUR_TOKEN>You can also use python-dotenv to load environment variables from your .env file.
Application Setup
Create app.py:
from flask import Flaskfrom upstash_redis import Redisapp = Flask(__name__)redis = Redis.from_env()@app.route('/')def index(): count = redis.incr('counter') return f'Page visited {count} times.'if __name__ == '__main__': app.run(debug=True)Running the Application
Run the Flask app locally:
python app.pyVisit http://127.0.0.1:5000/ in your browser, and you will see the counter increment with each refresh.
Code Breakdown
- Redis Setup: We first import Flask and the Upstash Redis client. Using
Redis.from_env(), we initialize the connection to our Redis database using the environment variables exported earlier. - Increment Counter: Each time the root route (
/) is accessed, Redis increments thecounterkey. This key-value pair is automatically created in Redis if it does not exist, and its value is incremented on each request. - Display the Count: The number of visits is returned in the response as plain text.