Introduction
A URL shortener is the perfect full-stack project: it touches databases, hashing, redirects, analytics, and a UI. In this post you’ll build one in Python with FastAPI + Streamlit + SQLite — deploy-ready in under 100 lines.
Architecture
┌──────────────┐ POST /shorten ┌──────────────┐
│ Streamlit │ ──────────────────► │ FastAPI │
│ UI │ ◄────────────────── │ (API) │
└──────────────┘ {short_url} └──────┬───────┘
│
┌──────────────┐ GET /{code} ┌──────┴───────┐
│ Browser │ ──────────────────► │ SQLite │
│ (redirect) │ ◄── 301 redirect ── │ (urls) │
└──────────────┘ └──────────────┘
Setup
mkdir url-shortener && cd url-shortener
python -m venv .venv && source .venv/bin/activate
pip install fastapi uvicorn streamlit requests
Step 1: Database model
# db.py
import sqlite3
from contextlib import contextmanager
DB = "urls.db"
@contextmanager
def get_db():
conn = sqlite3.connect(DB)
conn.row_factory = sqlite3.Row
try:
yield conn
conn.commit()
finally:
conn.close()
def init_db():
with get_db() as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS urls (
id INTEGER PRIMARY KEY AUTOINCREMENT,
code TEXT UNIQUE NOT NULL,
long_url TEXT NOT NULL,
clicks INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
Step 2: Short code generation
# shortener.py
import hashlib, base64
def make_code(long_url: str, length: int = 6) -> str:
"""Generate a short, unique-ish code from a URL."""
h = hashlib.sha256(long_url.encode()).digest()
code = base64.urlsafe_b64encode(h)[:length].decode()
return code.replace("=", "")
SHA-256 + base64 gives short, URL-safe codes. For production, use a counter (autoincrement ID → base62) to guarantee uniqueness.
Step 3: FastAPI backend
# api.py
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import RedirectResponse
from pydantic import BaseModel, HttpUrl
import shortener, db
db.init_db()
app = FastAPI(title="URL Shortener")
class ShortenIn(BaseModel):
url: HttpUrl
@app.post("/shorten")
def shorten(payload: ShortenIn):
long_url = str(payload.url)
code = shortener.make_code(long_url)
with db.get_db() as conn:
try:
conn.execute("INSERT INTO urls (code, long_url) VALUES (?, ?)", (code, long_url))
except sqlite3.IntegrityError:
pass # already exists
return {"code": code, "short_url": f"http://localhost:8000/{code}"}
@app.get("/{code}")
def redirect(code: str):
with db.get_db() as conn:
row = conn.execute("SELECT long_url FROM urls WHERE code = ?", (code,)).fetchone()
if not row:
raise HTTPException(404, "Not found")
conn.execute("UPDATE urls SET clicks = clicks + 1 WHERE code = ?", (code,))
return RedirectResponse(row["long_url"], status_code=301)
@app.get("/stats/{code}")
def stats(code: str):
with db.get_db() as conn:
row = conn.execute("SELECT long_url, clicks, created_at FROM urls WHERE code = ?", (code,)).fetchone()
if not row:
raise HTTPException(404, "Not found")
return dict(row)
Run: uvicorn api:app --reload --port 8000
Step 4: Streamlit UI
# app.py
import streamlit as st
import requests
API = "http://localhost:8000"
st.title("🔗 URL Shortener")
st.caption("Shorten, share, track clicks.")
long_url = st.text_input("Paste a long URL")
if st.button("Shorten") and long_url:
r = requests.post(f"{API}/shorten", json={"url": long_url})
if r.ok:
short = r.json()["short_url"]
st.success("Shortened!")
st.code(short)
st.write(f"Original: {long_url}")
# Stats lookup
code = st.text_input("Look up a short code (e.g. 'abc123')")
if code and st.button("Get stats"):
r = requests.get(f"{API}/stats/{code}")
if r.ok:
s = r.json()
st.write(f"**Original:** {s['long_url']}")
st.write(f"**Clicks:** {s['clicks']}")
st.write(f"**Created:** {s['created_at']}")
else:
st.error("Code not found")
Run: streamlit run app.py
Step 5: Add click analytics (bonus)
Track referrer and timestamp:
CREATE TABLE IF NOT EXISTS clicks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
code TEXT NOT NULL,
referrer TEXT,
clicked_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
In the redirect endpoint, insert a click row. Then build a Streamlit chart showing clicks over time per URL.
Step 6: Deploy
Backend (FastAPI): deploy to Render, Railway, or Fly.io (free tiers available). Or use Cloudflare Workers with D1.
Frontend (Streamlit): deploy to Streamlit Community Cloud (free). Set API env var to your deployed backend URL.
Common mistakes
- No uniqueness check — SHA-256 collisions are rare but possible. Use a counter (autoincrement → base62) for guaranteed uniqueness.
- Open redirect vulnerability — validate that
long_urlis a real URL (Pydantic’sHttpUrldoes this). - No rate limiting — spammers will abuse your shortener. Add rate limiting (e.g.,
slowapi). - Storing the full URL without normalization — strip trailing slashes, lowercase host.
- 302 instead of 301 — use 301 for permanent redirects (better for SEO and caching).
Key Concepts
- Short code = hash or counter → base62/base64
- 301 redirect = permanent redirect (cached by browsers)
- Click tracking = increment counter on redirect
- FastAPI + Streamlit = clean separation
- SQLite = zero-config database for prototypes
What to Try Next
- Add custom aliases (user picks the short code).
- Add expiration (links die after N days).
- Add QR code generation (use
qrcodelibrary). - Add auth so only logged-in users can create links.
- Deploy both to a single Docker Compose setup.
FAQ
URL shortener vs bit.ly — why build your own?
Learning, control, and privacy. bit.ly tracks everything and can delete your links. Your own shortener owns the data and the domain.
How do I handle collisions?
Use an autoincrement ID → base62 encoding (0-9, a-z, A-Z). IDs are unique by definition, so codes are unique. This is what bit.ly does.
Is SQLite enough for production?
For <10k links/day, yes. Beyond that, migrate to Postgres (Supabase) or use a key-value store (Redis). The code change is minimal — just swap the DB layer.