Python Project — URL Shortener (Flask + SQLite)
What this project does
This mini app takes a long URL (example: https://something.com/very/long/url)
and converts it into a short
when user opens that short URL → it redirects to original URL.
Tech Stack Used
| Thing | Why |
|---|---|
| Python | main language |
| Flask | micro web server |
| SQLite | tiny DB built into python |
| hash / random | generates the codes |
How it works
- user submits a URL on
/ - server stores it in SQLite table with a short id
- user receives a shortened link back
- opening
/<short_id>→ redirects
Perfect small backend starter project.
Features you can add later
- custom URL slug
- click count analytics
- QR code generation
code
from flask import Flask, request, redirect, jsonify
import sqlite3, string, random
app = Flask(__name__)
# init table on first run
with sqlite3.connect("urls.db") as db:
db.execute("CREATE TABLE IF NOT EXISTS urls(id TEXT PRIMARY KEY, original TEXT)")
# random short id generator
def generate_id(n=6):
return "".join(random.choices(string.ascii_letters + string.digits, k=n))
@app.post("/shorten")
def shorten():
data = request.get_json()
original = data.get("url")
short_id = generate_id()
with sqlite3.connect("urls.db") as db:
db.execute("INSERT INTO urls(id, original) VALUES(?, ?)", (short_id, original))
return jsonify({"short_url": f"http://localhost:5000/{short_id}"})
@app.get("/<short_id>")
def redirect_to_original(short_id):
with sqlite3.connect("urls.db") as db:
row = db.execute("SELECT original FROM urls WHERE id = ?", (short_id,)).fetchone()
if row:
return redirect(row[0])
return "Not Found", 404
@app.get("/")
def home():
return """
<form action="/shorten" method="post" onsubmit="event.preventDefault(); send()">
<input type="text" id="url" placeholder="Enter URL" style="width:400px"/>
<button type="submit">Shorten</button>
</form>
<script>
async function send(){
const url = document.getElementById('url').value;
const r = await fetch('/shorten', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({url})});
alert((await r.json()).short_url);
}
</script>
"""
if __name__ == "__main__":
app.run(debug=True)
how to run
pip install flask
python main.py
open it in browser