28 Jul 2023

Building a URL Shortener Service with Python and Flask

In the digital age, where sharing links has become an integral part of our online communication, URL shorteners play a crucial role in making long and complex URLs more manageable and shareable. In this tutorial, we will explore how to build a URL shortener service using Python and Flask, a popular web framework. By the end of this tutorial, you will have a functional URL shortener that you can deploy and use.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of Python programming, as well as some familiarity with Flask. Additionally, make sure you have Python and Flask installed on your machine.

Setting up the Project

  1. Create a new directory for your project and navigate into it using the command line.
  2. Create a virtual environment by running the command: python -m venv venv.
  3. Activate the virtual environment with:
    • On Windows: venv\Scripts\activate
    • On macOS/Linux: source venv/bin/activate
  4. 4. Install Flask by running: pip install flask.
  5. 5. Create a new file called app.py and open it in your preferred code editor.

Creating the Flask Application

Import the necessary modules

from flask import Flask, render_template, request, redirect
import string
import random

Initialize the Flask application

app = Flask(__name__)

Define the route for the home page

@app.route('/')
def home():
    return render_template('index.html')

Create a route to handle URL shortening

@app.route('/shorten', methods=['POST'])
def shorten():
    original_url = request.form['url']
    short_url = generate_short_url()
    # Save the original and short URLs to a database or file
    return render_template('result.html', original_url=original_url, short_url=short_url)

Define a function to generate a random short URL

def generate_short_url():
    characters = string.ascii_letters + string.digits
    short_url = ''.join(random.choice(characters) for _ in range(6))
    # Check if the short URL is already in use and generate a new one if necessary
  return short_url

Run the Flask application

if __name__ == '__main__':
    app.run()

Creating the HTML Templates

  1. Create a new folder called  templates in your project directory.
  2. Inside the  templates  folder, create two HTML files: index.html and result.html .

index.html should contain a form for users to enter a long URL to be shortened

<!DOCTYPE html>
<html>
<head>
    <title>URL Shortener</title>
</head>
<body>
    <h1>URL Shortener</h1>
    <form action="/shorten" method="POST">
        <input type="text" name="url" placeholder="Enter a URL">
        <input type="submit" value="Shorten">
    </form>
</body>
</html>

result.html should display the original URL and the shortened URL

<!DOCTYPE html>
<html>
<head>
    <title>URL Shortener</title>
</head>
<body>
    <h1>URL Shortener</h1>
    <p>Original URL: {{ original_url }}</p>
    <p>Short URL: <a href="{{ short_url }}">{{ short_url }}</a></p>
</body>
</html>

Testing the URL Shortener

  1. Start the Flask application by running  python app.py  in the command line.
  2. Open your web browser and navigate to http://localhost:5000 .
  3. Enter a long URL in the input field and click the "Shorten" button.
  4. You will be redirected to a page displaying the original URL and the shortened URL.
  5. Click on the shortened URL to test if it redirects you to the original URL.

Conclusion

Congratulations! You have successfully built a URL shortener service using Python and Flask. You have learned how to create a basic Flask application, generate random short URLs, and render HTML templates. Feel free to further enhance the functionality of your URL shortener by adding features like URL validation, user authentication, and persistence using a database. With this foundation, you can now explore more advanced concepts and build upon your URL shortener service to suit your specific needs.