Skip to main content

Command Palette

Search for a command to run...

Build a Simple URL Shortener in Python

Published
3 min read
Build a Simple URL Shortener in Python

Introduction

Long URLs are cumbersome to share and prone to being broken in emails or messages. A URL shortener compresses long links into short, manageable ones — like what Bitly or TinyURL does.

In this guide, you’ll learn how to build a URL shortener using Python that works locally. You’ll also see how to store and retrieve original URLs using a dictionary-based system.

This is ideal for educational purposes, personal tools, or forming the foundation of a more complex web-based service.

How Does a URL Shortener Work?

A typical URL shortener performs three tasks:

  1. Accepts a long URL from the user.

  2. Generates a short code using a hash or unique ID.

  3. Stores the mapping between the short code and the original URL.

When a user accesses the short code (like https://short.ly/abc123), the service redirects them to the original long URL.

What You’ll Learn

  • Hashing and encoding URLs

  • Managing a mapping system

  • Making a short, reusable script

  • Optional: Saving mappings to a file or database

Step-by-Step Script (Local Version)

We’ll create a simple terminal-based tool that:

  • Shortens URLs using a hash

  • Lets you retrieve original URLs

  • Stores mappings in memory (or optionally in a file)

Step 1: Import Required Modules

import hashlib
import base64
  • hashlib: Generates a unique hash from the long URL.

  • base64: Encodes binary data to ASCII to keep the short link URL-safe.

Step 2: Set Up a Dictionary to Store URL Mappings

url_mapping = {}

This dictionary holds short codes as keys and original URLs as values.

Step 3: Define the Shortening Function

def shorten_url(long_url):
    # Generate a SHA-256 hash of the URL
    hash_object = hashlib.sha256(long_url.encode())
    hash_digest = hash_object.digest()

    # Encode the hash in base64 and take the first 6 characters
    short_code = base64.urlsafe_b64encode(hash_digest)[:6].decode()

    # Save mapping
    url_mapping[short_code] = long_url
    return f"http://short.ly/{short_code}"

Explanation:

  • The sha256 hash ensures uniqueness.

  • base64.urlsafe_b64encode ensures the short code is URL-safe (no special chars).

  • We limit the short code to 6 characters for brevity.

Step 4: Create a Function to Retrieve the Original URL

def retrieve_url(short_code):
    return url_mapping.get(short_code, "URL not found")

This function looks up the original long URL from the short code.

Step 5: User Interface with Console Input

if __name__ == "__main__":
    while True:
        print("\n--- URL Shortener ---")
        print("1. Shorten URL")
        print("2. Retrieve URL")
        print("3. Exit")

        choice = input("Choose an option (1/2/3): ")

        if choice == "1":
            long_url = input("Enter the original URL: ")
            short = shorten_url(long_url)
            print(f"Shortened URL: {short}")

        elif choice == "2":
            code = input("Enter the short code (e.g., abc123): ")
            full_url = retrieve_url(code)
            print(f"Original URL: {full_url}")

        elif choice == "3":
            break
        else:
            print("Invalid option. Try again.")

Example Usage

--- URL Shortener ---
1. Shorten URL
2. Retrieve URL
3. Exit
Choose an option (1/2/3): 1
Enter the original URL: https://www.example.com/page?id=12345
Shortened URL: http://short.ly/NrkjYw

--- URL Shortener ---
1. Shorten URL
2. Retrieve URL
3. Exit
Choose an option (1/2/3): 2
Enter the short code (e.g., abc123): NrkjYw
Original URL: https://www.example.com/page?id=12345

Key Concepts Recap

  • URL shortening is achieved by hashing and encoding

  • Short codes should be unique and URL-safe

  • You must store a mapping between short code and original URL to support redirection

  • Shortener scripts can grow into full web apps or APIs

Final Thoughts

You now have a working local URL shortener built with just a few lines of Python. This kind of utility can be extended for use in email marketing, internal tools, or as a lightweight backend service.

If you want help turning this into a web-based service (with Flask, Django, or FastAPI), or storing the data in a file or database, just let me know!