Creating a URL Shortener Service with Python

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setup
  4. Creating a URL Shortener
  5. Conclusion

Introduction

In this tutorial, we will learn how to create a URL shortener service using Python. URL shorteners are tools that shorten long URLs into shorter, more manageable links. They are commonly used in social media platforms, email signatures, and other web-based applications.

By the end of this tutorial, you will be able to create a basic URL shortener service that takes long URLs as input and generates shortened URLs as output.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of Python programming. Additionally, you will need to have the following installed on your machine:

  • Python (version 3.6 or higher)
  • Flask (a Python web framework)

Setup

  1. Create a new directory on your computer where you want to store the project files.
  2. Open the command prompt or terminal and navigate to the newly created directory.
  3. Create a new virtual environment by running the following command:
    python -m venv env
    
  4. Activate the virtual environment:
    • On Windows:
      env\Scripts\activate
      
    • On macOS/Linux:
      source env/bin/activate
      
  5. Install Flask by running the following command:
    pip install flask
    

    Creating a URL Shortener

  6. Create a new Python file in your project directory called app.py.
  7. Import the necessary modules:
    from flask import Flask, render_template, request, redirect
    import string
    import random
    
  8. Create an instance of the Flask class:
    app = Flask(__name__)
    
  9. Define a route for the home page:
    @app.route('/')
    def home():
        return render_template('index.html')
    
  10. Create a function to generate a random alphanumeric string for the shortened URL:
    def generate_shortened_url():
        characters = string.ascii_letters + string.digits
        return ''.join(random.choice(characters) for _ in range(6))
    
  11. Define a route to handle the form submission and generate the shortened URL:
    @app.route('/shorten', methods=['POST'])
    def shorten():
        long_url = request.form['long_url']
        shortened_url = generate_shortened_url()
        return render_template('result.html', long_url=long_url, shortened_url=shortened_url)
    
  12. Create HTML templates for the home page (index.html) and the result page (result.html) in a templates folder in your project directory.
  13. Write the following HTML code in index.html:
    <!DOCTYPE html>
    <html>
    <head>
        <title>URL Shortener</title>
    </head>
    <body>
        <h1>URL Shortener</h1>
        <form action="/shorten" method="post">
            <label for="long_url">Enter a long URL:</label>
            <input type="text" id="long_url" name="long_url">
            <input type="submit" value="Shorten">
        </form>
    </body>
    </html>
    
  14. Write the following HTML code in result.html:
    <!DOCTYPE html>
    <html>
    <head>
        <title>URL Shortener - Result</title>
    </head>
    <body>
        <h1>URL Shortener - Result</h1>
        <p>Long URL: </p>
        <p>Shortened URL: </p>
    </body>
    </html>
    
  15. Run the Flask application:
    flask run
    
  16. Open your web browser and navigate to http://localhost:5000 to access the URL shortener service.
  17. Enter a long URL and click the “Shorten” button.
  18. You will be redirected to a page displaying the long URL and the generated shortened URL.

Conclusion

In this tutorial, we have learned how to create a URL shortener service using Python and Flask. By following the step-by-step instructions, you should now have a basic understanding of how to build a simple URL shortener.

Keep in mind that this is just a basic example, and there are many additional features and improvements you can make to your URL shortener service. Some possible enhancements include persisting the shortened URLs in a database, adding analytics tracking, or customizing the URL format.

Feel free to explore and expand upon this project to make it your own!