Beginner Mini-Project #4 · Full-Stack Bridge: All Weekend Builds →
Backend Bridge · Python + Flask + JSON
🔗 Mini URL Shortener
Your first backend bridge: generate custom or random short slugs, store mappings in a JSON file, track click counts, and handle HTTP redirects.
Last updated: November 2026 · 10 min read · ~45 mins build time
A URL shortener maps a short key (like /py42) to a full destination URL. When a visitor opens the short route, Flask looks up the key in links.json, increments its click count, and returns redirect(target_url).
What you learn: Flask GET/POST routes, dynamic URL parameters (<slug>), secrets token generation, safe JSON file persistence, and URL scheme validation.
🚀 Interactive Sandbox
Test creating custom short links, simulating clicks, and inspecting live JSON storage on a dedicated full-screen page.
Mini URL Shortener — Live Sandbox
Create short links with random or custom aliases, trigger simulated visits to watch click counters climb, and inspect the live JSON payload in real time.
Open Live Demo📦 Complete Flask Application (app.py)
Install Flask with pip install flask, save this code as app.py, and run python app.py.
import json
import os
import re
import secrets
import string
from datetime import datetime
from flask import Flask, abort, redirect, render_template_string, request, url_for
app = Flask(__name__)
DATA_FILE = "links.json"
SLUG_PATTERN = re.compile(r"^[a-zA-Z0-9_-]{3,24}$")
def load_links():
if not os.path.exists(DATA_FILE):
return {}
try:
with open(DATA_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except (json.JSONDecodeError, OSError):
return {}
def save_links(links):
with open(DATA_FILE, "w", encoding="utf-8") as f:
json.dump(links, f, indent=2)
def generate_slug(existing_keys, length=6):
alphabet = string.ascii_letters + string.digits
while True:
slug = "".join(secrets.choice(alphabet) for _ in range(length))
if slug not in existing_keys:
return slug
def is_valid_url(url):
return url.startswith("http://") or url.startswith("https://")
HTML_TEMPLATE = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mini URL Shortener — MAK UI Studio</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: system-ui, -apple-system, sans-serif;
background: #020617; color: #e2e8f0;
padding: 2rem 1rem; line-height: 1.5;
}
.wrap { max-width: 760px; margin: 0 auto; }
h1 { font-size: 1.8rem; color: #fff; margin-bottom: 0.35rem; }
.sub { color: #94a3b8; font-size: 0.92rem; margin-bottom: 1.5rem; }
.card {
background: #0f172a; border: 1px solid #1e293b;
border-radius: 14px; padding: 1.25rem; margin-bottom: 1.5rem;
}
.row { display: grid; grid-template-columns: 2fr 1fr auto; gap: 0.65rem; }
input {
background: #020617; border: 1px solid #334155; color: #fff;
padding: 0.7rem 0.85rem; border-radius: 8px; font-size: 0.9rem; width: 100%;
}
input:focus { outline: none; border-color: #38bdf8; }
button {
background: #3b82f6; color: #fff; border: none; font-weight: 700;
padding: 0.7rem 1.2rem; border-radius: 8px; cursor: pointer;
}
button:hover { background: #2563eb; }
.alert {
background: rgba(239, 68, 68, 0.15); border: 1px solid #ef4444;
color: #fca5a5; padding: 0.65rem 0.9rem; border-radius: 8px;
margin-bottom: 1rem; font-size: 0.85rem;
}
.link-item {
display: flex; justify-content: space-between; align-items: center;
gap: 1rem; padding: 0.85rem 0; border-bottom: 1px solid #1e293b;
}
.link-item:last-child { border-bottom: none; }
.slug { color: #38bdf8; font-weight: 700; text-decoration: none; font-size: 0.95rem; }
.dest { color: #94a3b8; font-size: 0.8rem; word-break: break-all; }
.badge {
background: #1e293b; color: #34d399; font-weight: 700;
padding: 0.25rem 0.65rem; border-radius: 999px; font-size: 0.78rem;
white-space: nowrap;
}
@media (max-width: 640px) { .row { grid-template-columns: 1fr; } }
</style>
</head>
<body>
<div class="wrap">
<h1>🔗 Mini URL Shortener</h1>
<p class="sub">Python + Flask + JSON file storage with instant click tracking.</p>
{% if error %}
<div class="alert">{{ error }}</div>
{% endif %}
<form class="card" method="POST" action="/">
<div class="row">
<input type="url" name="url" placeholder="https://makuistudio.com/courses/python" required>
<input type="text" name="custom_slug" placeholder="Custom alias (optional)">
<button type="submit">Shorten</button>
</div>
</form>
<div class="card">
<h2 style="font-size: 1rem; color: #fff; margin-bottom: 0.75rem;">Saved Short Links ({{ links|length }})</h2>
{% if links %}
{% for slug, info in links.items()|reverse %}
<div class="link-item">
<div>
<a class="slug" href="/{{ slug }}" target="_blank">{{ request.host_url }}{{ slug }}</a>
<div class="dest">→ {{ info.url }}</div>
</div>
<span class="badge">{{ info.clicks }} clicks</span>
</div>
{% endfor %}
{% else %}
<p style="color: #64748b; font-size: 0.88rem;">No links shortened yet. Paste a URL above to create your first short link.</p>
{% endif %}
</div>
</div>
</body>
</html>
"""
@app.route("/", methods=["GET", "POST"])
def index():
links = load_links()
error = None
if request.method == "POST":
raw_url = request.form.get("url", "").strip()
custom_slug = request.form.get("custom_slug", "").strip()
if not is_valid_url(raw_url):
error = "Please enter a valid URL starting with http:// or https://"
elif custom_slug:
if not SLUG_PATTERN.match(custom_slug):
error = "Custom alias must be 3–24 characters (letters, numbers, hyphens, underscores)."
elif custom_slug in links:
error = f"The alias '{custom_slug}' is already taken. Pick another one."
else:
links[custom_slug] = {
"url": raw_url,
"clicks": 0,
"created_at": datetime.utcnow().isoformat() + "Z",
}
save_links(links)
return redirect(url_for("index"))
else:
slug = generate_slug(links)
links[slug] = {
"url": raw_url,
"clicks": 0,
"created_at": datetime.utcnow().isoformat() + "Z",
}
save_links(links)
return redirect(url_for("index"))
return render_template_string(HTML_TEMPLATE, links=links, error=error)
@app.route("/<slug>")
def follow_slug(slug):
links = load_links()
entry = links.get(slug)
if not entry:
abort(404)
entry["clicks"] += 1
save_links(links)
return redirect(entry["url"], code=302)
if __name__ == "__main__":
app.run(debug=True, port=5000)
How the URL Shortener works (6 steps)
load_links & save_links)Instead of requiring a database server on day one, all shortened URLs live inside a human-readable links.json dictionary keyed by slug. Wrapping json.load() in a try/except ensures a missing or empty file never crashes the app.
When the user leaves the custom alias field blank, secrets.choice() builds a 6-character alphanumeric string and loops until it finds one not already present in links.json.
Before saving any entry, is_valid_url() enforces http:// or https:// prefixes, while SLUG_PATTERN restricts custom aliases to safe URL characters and prevents overwriting routes.
After saving a new link on a POST request, Flask immediately returns redirect(url_for("index")). That prevents browsers from resubmitting duplicate links if the user hits Refresh.
/<slug>)Flask captures any path segment as slug, looks it up in links.json, increments entry["clicks"] += 1, writes the updated JSON back to disk, and issues an HTTP 302 redirect.
If someone visits a non-existent slug like /unknown123, abort(404) returns a proper HTTP 404 Not Found status instead of throwing a Python KeyError.
🛠️ Weekend Extension Challenges
Add an optional expires_at timestamp field. Check the current UTC time inside follow_slug() and return a 410 Gone error if the link has expired.
Add a POST /delete/<slug> route with a small delete button next to each link so users can clean up old URLs from the dashboard.
Once you understand JSON persistence, swap load_links() and save_links() for Python's built-in sqlite3 module—just like Stage 3 of our 4-Stage App Builds.
⚠️ Common mistakes
- Allowing arbitrary URL schemes. Without checking for
http://orhttps://, users can storejavascript:alert(1)payloads. - Using
randominstead ofsecrets. Standard pseudo-random generators are predictable;secrets.choice()is built for tokens and slugs. - Forgetting Post/Redirect/Get. Rendering HTML directly after a
POSTcauses duplicate short links when the user refreshes the page. - Returning HTTP 301 instead of 302 during testing. Browsers cache
301 Permanent Redirectaggressively, bypassing your Flask server and breaking click tracking on repeat visits.
❓ Frequently asked questions
How does a URL shortener work under the hood?
A URL shortener maps a short alphanumeric code (slug) to a long destination URL in storage. When someone visits /slug, the server looks up the destination, increments a click counter, and returns an HTTP 302 redirect response.
Why use JSON instead of a database for this mini-project?
Storing links in a local links.json file lets you inspect the saved mappings in any text editor and persist data across server restarts without configuring SQLite or PostgreSQL first.
Why use HTTP 302 instead of 301 for click tracking?
HTTP 301 tells browsers to cache the redirect permanently and skip your server on future visits. HTTP 302 (Temporary Redirect) ensures every click hits your Flask route so your analytics stay accurate.
How does the live browser demo work without a Python server?
Because static hosting does not run Python processes, our interactive demo simulates the Flask routing table, click analytics, and redirect preview right inside your browser using localStorage.