Freedom Sale
Independence Day Special — Unlock the AI Path 70% off our most popular AI course · Limited time offer
--Days
--Hrs
--Min
--Sec
Claim Your Discount
Python ✦ Intermediate ⏱ 60 minutes

🔗 Build a URL Shortener with Python and Flask

Build your own URL shortener like bit.ly — in Python. You'll learn Flask web framework basics, how HTTP redirects work, and how to build and serve a simple web form. No database required.

🎯 What You’ll Build

A local web app where you paste a long URL, get a short code back (like /go/abc123), and anyone who visits that short URL gets redirected to the original. Runs in your browser, powered by Flask.

📋 What You’ll Need

Flask is Python's most popular micro-framework for building web apps. Once you understand it, you can build APIs, dashboards, and full web apps. Let's start with something practical.

1

Install Flask

Flask is a micro web framework — small, fast, and beginner-friendly. Install it:

pip install flask

That's the only dependency you need. Flask comes with a built-in development server, so you don't need Apache or Nginx.

2

Create the app skeleton

Create a file called app.py. Here's the minimum Flask app:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
return 'Hello from Flask!'

if __name__ == '__main__':
app.run(debug=True)

Run it with python app.py and open http://127.0.0.1:5000 in your browser. You should see "Hello from Flask!".

3

Add URL storage and a shortener function

We'll store URLs in a Python dictionary (for simplicity). Add this above the routes:

import random
import string
from flask import Flask, redirect, request, render_template_string

app = Flask(__name__)
url_store = {} # short_code -> original_url

def generate_code(length=6):
chars = string.ascii_letters + string.digits
return ''.join(random.choices(chars, k=length))
💡 Why a dict? For a production app you'd use a database. But for learning Flask, a dictionary keeps things simple and removes the database setup step.
4

Build the home page with a form

Replace the home route with a real HTML form:

HTML = '''
<!DOCTYPE html><html><body style="font-family:sans-serif;max-width:500px;margin:60px auto;padding:0 20px">
<h1>🔗 URL Shortener</h1>
<form method="POST" action="/shorten">
<input name="url" type="url" placeholder="Paste a long URL..." required
style="width:100%;padding:10px;font-size:1rem;margin-bottom:10px">
<button type="submit" style="background:#F59C0D;color:#fff;padding:10px 20px;border:none;border-radius:6px;font-size:1rem;cursor:pointer">
Shorten</button>
</form>
{% if short_url %}<p>Short URL: <a href="{{ short_url }}">{{ short_url }}</a></p>{% endif %}
</body></html>'''


@app.route('/')
def home():
return render_template_string(HTML, short_url=None)

render_template_string() lets us embed a Jinja2 template directly in the Python file — no separate HTML files needed for small apps.

5

Add the /shorten route

This route handles the form submission and creates the short code:

@app.route('/shorten', methods=['POST'])
def shorten():
original = request.form['url']
code = generate_code()
url_store[code] = original
short = f'http://127.0.0.1:5000/go/{code}'
return render_template_string(HTML, short_url=short)

The form submits a POST request to /shorten, which generates a 6-character code, stores the mapping, and shows the short URL back to the user.

6

Add the redirect route

This is the most important part — when someone visits a short URL, redirect them:

@app.route('/go/<code>')
def go(code):
original = url_store.get(code)
if original:
return redirect(original)
return 'Short URL not found', 404

/go/<code> is a dynamic route — Flask captures whatever comes after /go/ and passes it as the code argument. redirect() sends the browser to the original URL with a 302 status.

7

Run it and test

Start the server:

python app.py

Open http://127.0.0.1:5000. Paste any long URL and click Shorten. Copy the short URL and paste it in a new tab — you'll be redirected instantly.

Output
* Running on http://127.0.0.1:5000
* Debug mode: on
127.0.0.1 - - [GET /go/xK9p2m] -> Redirecting to https://...
⚠ Note: URLs are stored in memory — they reset when you restart the server. For persistence, replace the dict with SQLite using sqlite3 or Flask-SQLAlchemy.
🎉

You did it!

You built a working URL shortener with Flask — complete with a web form, short code generation, and HTTP redirects. You now understand the core of how every web framework works.

🚀 Take It Further

← All Tutorials

Found something wrong?

Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.