Building a URL Shortener with Flask and Redis
A bare bones implementation of a link shortener

In this article, we will dive into the process of building a URL shortener using the Flask web framework and Redis, an in-memory data store. URL shorteners are essential tools that transform long URLs into short and easily shareable links.
What’s a URL Shortener?
Is a simple program in which it reduces the lenght of a given URL. Ideally, the shortened URL is easier to remember and track than the original URL.
Designing a URL shortener
The heart of our URL shortener lies in its ability to generate short, unique, and recognizable URLs that correspond to the longer destination URLs. To achieve this, we’ll employ a combination of techniques including encoding algorithms and data storage.
- Encoding Algorithm: The core of generating short URLs involves encoding the original URL to create a shorter representation. While various encoding algorithms exist, for simplicity, we’ll use Base62 encoding. Base62 uses a character set of 62 characters (26 lowercase letters, 26 uppercase letters, and 10 digits), enabling us to generate compact URLs with a good mix of characters. This will allow a total of
62^k
wherek
is the lenght we desire of the shortened URL. - Mapping to Original URLs: Once we’ve encoded the original URL, we need a way to map the short URL back to its original counterpart. This is where Redis comes into play. Redis, being an in-memory data store, provides fast data retrieval and is well-suited for storing key-value pairs, making it an excellent choice for our short URL mapping.
- Generating a Unique Identifier: Before we proceed with encoding, we need to generate a unique identifier for each original URL.
- Storing in Redis: With the unique identifier in hand, we can encode it using Base62 to generate a short URL. We then store the mapping of the short URL to the original URL in Redis, using the unique identifier as the key and the original URL as the value. This mapping allows us to quickly retrieve the original URL when a short URL is requested.
- Ensuring Uniqueness: As part of this process, it’s important to ensure that the generated short URLs are unique to avoid conflicts. We can achieve this by checking whether a generated short URL is already present in Redis. If it is, we can generate another one until we find a unique short URL.
Thus the interaction between the layers would be a simple 3 layer application, as shown here:

Development
Setting up the enviroment
Before we dive into building the URL shortener, we need to set up the development environment.
- Create and activate a virtual enviroment
Navigate to the project directory in your terminal and create a virtual environment to isolate the project dependencies:
python -m venv venv
venv\Scripts\activate
pip install Flask redis
2. Project Structure
We’ll organize our project in the following structure to allow for a “clean” work enviroment:
URLShortener/
├── venv/ # Virtual environment folder
├── app/
│ ├── static/ # Static files (CSS, images)
│ ├── templates/ # HTML templates
│ ├── __init__.py # Flask app initialization
│ └── routes.py # URL routing and logic
│
└── run.py # Run the Flask app
Implementing
First we’ll create an HTML file which will serve as our point to create new shortened URLs. To do this, we create a new HTML template inside templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>URL Shortener</title>
<link
rel="stylesheet"
type="text/css"
href="{{ url_for('static', filename='styles.css') }}"
/>
</head>
<body>
<div class="container">
<h1>URL Shortener</h1>
<form method="post">
<input type="url" name="url" placeholder="Enter URL" />
<button type="submit">Shorten</button>
</form>
{% if short_url %}
<p>
Short URL:
<a href="{{ url_for('redirect_to_original_url', short_url=short_url) }}"
>{{host_url}}/{{ short_url }}</a
>
</p>
{% endif %}
</div>
</body>
</html>
This HTML template represents the user interface of a URL shortener web application. It basically creates the following web page.

Now that we have an HTML template to work with, we’ll do the actual functionality of the shortener, to do that we’ll modify our routes.py
:
from flask import render_template, request, redirect, url_for
from app import app
import redis
import string
import random
# The Base62 digits present in our shortened URL
SHORT_URL_LEN = 6
# Where the web service is hosted
HOST_NAME = "http://localhost:5000"
# Connect to Redis server
redis_client = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
# Generates a random Base62 string containing SHORT_URL_LEN characters
def generate_short_url():
# All possible characters
characters = string.ascii_letters + string.digits
# Randomly assings 6 characters of all the possible characters
short_url = ''.join(random.choice(characters) for _ in range(SHORT_URL_LEN))
return short_url
# Route that generates the shortened URL and that display
# the HTML template
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
# Get the original URL
original_url = request.form['url']
# Generates the ID which is the shortened URL
short_url = generate_short_url()
# Store the mapping in Redis
redis_client.set(short_url, original_url)
# Display the template HTML with the generated url
return render_template('index.html', short_url=short_url, host_url = HOST_NAME)
return render_template('index.html')
# Route to redirect to a particular shortened url if found
@app.route('/<short_url>')
def redirect_to_original_url(short_url):
original_url = redis_client.get(short_url)
if original_url:
return redirect(original_url)
else:
return "Short URL not found", 404
We’ll need to also edit our __init__.py
and our run.py
to allow a proper execution of the web application
# run.py
from app import app
if __name__ == '__main__':
app.run(debug=True)
# __init__.py
from flask import Flask
app = Flask(__name__)
from app import routes
Results
And just like that, we have a working URL Shortener, as shown bellow!
Conclusions
We rapidly developed a URL shortener using Flask and Redis. We chose Redis due to its ability to facilitate swift access to key-value pairs, making it an ideal fit for a URL shortener. While this application covers the fundamental functionality, there’s room for enhancement. For instance:
- Adding link history and stats for a particular link
- Adding the posibility of custom links
- Adding accounts
- Improving the visuals
- Anything your heart desires!
The code is available in this Github Repository. If you liked the content, please don’t doubt to follow!
In Plain English
Thank you for being a part of our community! Before you go:
- Be sure to clap and follow the writer! 👏
- You can find even more content at PlainEnglish.io 🚀
- Sign up for our free weekly newsletter. 🗞️
- Follow us on Twitter, LinkedIn, YouTube, and Discord.