Creating a URL shortener is a useful web application that can help users convert long URLs into short, easy-to-share links. In this guide, we'll walk you through the process of building a URL shortener with Flask, a Python web framework. You'll learn how to set up your Flask application, create routes for shortening and redirecting URLs, and generate unique short codes for each URL.

Step 1: Setting Up Your Flask Application

Before you can build a URL shortener, make sure you have a Flask application. If not, you can create a basic Flask app like this:

from flask import Flask, render_template, request, redirect
app = Flask(__name)

Step 2: Creating Routes

Create routes to handle shortening and redirecting URLs. Here's an example of a route for shortening URLs:

url_map = {}
def index():
return render_template('index.html')
@app.route('/shorten', methods=['POST'])
def shorten_url():
long_url = request.form['long_url']
short_code = generate_short_code()
url_map[short_code] = long_url
return render_template('shortened.html', short_url=f'/{short_code}')
def redirect_to_url(short_code):
long_url = url_map.get(short_code)
if long_url:
return redirect(long_url)
return 'URL not found.'

Step 3: Generating Short Codes

Create a function to generate unique short codes for URLs. You can customize the logic for generating short codes according to your preferences.

import random
import string
def generate_short_code():
characters = string.ascii_letters + string.digits
short_code = ''.join(random.choice(characters) for _ in range(6))
return short_code

Step 4: Creating HTML Templates

Create HTML templates for rendering the URL shortener. Here's an example of an "index.html" template:

<!DOCTYPE html>
<title>URL Shortener</title>
<h1>URL Shortener</h1>
<form method="POST" action="/shorten">
<label for="long_url">Long URL:</label>
<input type="url" id="long_url" name="long_url" required>
<input type="submit" value="Shorten URL">

Additionally, create a "shortened.html" template for displaying the shortened URL.

Step 5: Running Your Application

As usual, run your Flask application with the following code at the end of your script:

if __name__ == '__main__':

Now, you can run your application with the command python and access your URL shortener.


Building a URL shortener with Flask is a practical project that demonstrates the capabilities of web development with Python. You've learned how to set up your application, create routes for shortening and redirecting URLs, and generate unique short codes. This project can be extended by adding features like custom short codes, analytics, and user accounts.