Build a Simple URL Shortener in Python — No Framework Required!

Ever wondered how Bitly or TinyURL shortens long links into just a few characters? In this post, we’ll build a fully functional URL shortener using pure Python — no Flask, no Django, just the standard library + a tiny storage system.

Perfect for learning about:

  • Hashing and encoding

  • Dictionaries as in-memory databases

  • Basic URL redirection logic


🎯 What We’ll Build

plaintextCopyEditLong URL ➡️ "https://openai.com/research/gpt-4o"
Short Code ➡️ "k1Dz2A"

You store and retrieve links like:
  shorten("https://...") → "k1Dz2A"
  expand("k1Dz2A") → "https://..."

🧱 Step 1: Set Up the Code Structure

Create a file url_shortener.py:

pythonCopyEditimport hashlib
import base64

🔧 Step 2: Encode URLs

Use SHA-256 and Base64 to create short but unique codes:

pythonCopyEditdef shorten_url(long_url):
    hash_object = hashlib.sha256(long_url.encode())
    b64_encoded = base64.urlsafe_b64encode(hash_object.digest())
    short_code = b64_encoded[:6].decode()  # 6-char short code
    return short_code

💾 Step 3: Save and Retrieve Mappings

pythonCopyEdit# In-memory database (use pickle or JSON to persist if needed)
url_map = {}

def store_url(long_url):
    short_code = shorten_url(long_url)
    url_map[short_code] = long_url
    return short_code

def retrieve_url(short_code):
    return url_map.get(short_code, "Not found")

✅ Step 4: Try It Out

pythonCopyEditif __name__ == "__main__":
    long = input("Enter a long URL: ")
    code = store_url(long)
    print("Shortened Code:", code)

    recovered = retrieve_url(code)
    print("Original URL:", recovered)

🧪 Sample Run

bashCopyEditEnter a long URL: https://openai.com/research/gpt-4o
Shortened Code: 1d8a9F
Original URL: https://openai.com/research/gpt-4o

🛠 Bonus: Make It a Command-Line Tool

bashCopyEditpython url_shortener.py shorten "https://example.com"
python url_shortener.py expand "k1Dz2A"

Use argparse to add this easily (see CLI blog post!).


📡 Want to Go Further?

  • Add a Flask or FastAPI interface

  • Store mappings in a real DB like SQLite

  • Add expiration for links

  • Track number of clicks

0
Subscribe to my newsletter

Read articles from Ashraful Islam Leon directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ashraful Islam Leon
Ashraful Islam Leon

Passionate Software Developer | Crafting clean code and elegant solutions