Creating a URL shortener service is a common web development project that allows you to convert long URLs into shorter, more manageable links. In this guide, we'll explore how to build a simple URL shortener service using Flask, a Python web framework. By following this guide, you'll learn how to create a basic URL shortening application, generate short URLs, and redirect users to the original URLs. This project is a great introduction to web development and can be expanded with additional features and optimizations.

Step 1: Setting Up Your Flask Application

Start by setting up your Flask application and creating a directory structure. Here's a sample structure:


Step 2: Creating the URL Shortener Application

Create a Flask application for the URL shortener. Here's an example of the Python code:

from flask import Flask, render_template, request, redirect
import shortuuid
app = Flask(__name)
# Store original URLs and their corresponding short URLs
url_mapping = {}
def index():
return render_template('index.html')
@app.route('/shorten', methods=['POST'])
def shorten_url():
original_url = request.form['original_url']
short_url = shortuuid.uuid()[:8] # Generate a short unique identifier
url_mapping[short_url] = original_url
return render_template('shortened.html', original_url=original_url, short_url=short_url)
def redirect_to_original(short_url):
original_url = url_mapping.get(short_url)
if original_url:
return redirect(original_url)
return 'Short URL not found.'
if __name__ == '__main__':

Step 3: Creating HTML Templates

Create HTML templates for the URL shortener service. Here's an example of templates:

<!-- templates/index.html -->
<!DOCTYPE html>
<title>URL Shortener</title>
<h1>URL Shortener</h1>
<h2>Shorten a URL</h2>
<form method="POST" action="/shorten">
<input type="url" name="original_url" placeholder="Enter your URL" required>
<button type="submit">Shorten</button>
<!-- templates/shortened.html -->
<!DOCTYPE html>
<title>Shortened URL</title>
<h1>Shortened URL</h1>
<h2>Your original URL:</h2>
<p>{{ original_url }}</p>
<h2>Your shortened URL:</h2>
<p><a href="/{{ short_url }}">{{ short_url }}</a></p>

Step 4: Running Your URL Shortener

Run your Flask URL shortener application using the following command:


Access your URL shortener service in a browser, enter a long URL, and obtain a shortened link.


Building a simple URL shortener service with Flask is a fun and educational project. By following the steps in this guide, you can create a basic URL shortening application, generate short URLs, and redirect users to the original links. This project can be expanded with additional features like user accounts, analytics, and custom short URL aliases. It serves as a great starting point for web development and Python programming.