Unfortunately, the short link you have entered is a bad link, has expired, or does not exist!
SHORTEN WORLD
https://ln.run/blog/how-to-build-your-own-url-shortener-with-php-or-node-js
https://ln.run/blog/fun-and-creative-uses-of-short-links
https://ln.run/blog/how-to-build-your-own-url-shortener-with-php-or-node-js
https://ln.run/blog/fun-and-creative-uses-of-short-links
https://ln.run/blog/how-to-build-your-own-url-shortener-with-php-or-node-js
https://ln.run/blog/fun-and-creative-uses-of-short-links
In the world of digital marketing, data sharing, and social media, long URLs are often a problem. They are hard to share, remember, and manage. That’s where URL shorteners come in. These tools condense long web addresses into compact, shareable links. For developers, creating a custom URL shortener can be a practical and educational project. Python, with its simplicity and versatility, is an ideal language for the job.
In this comprehensive guide, we’ll explore the ins and outs of URL shortening using Python, from the fundamentals of how it works to building your own mini URL shortening service.
URL shortening is the process of converting a long URL into a short, manageable link. For example:
https://www.example.com/blog/posts/how-to-use-python-url-shortener
→https://sho.rt/abc123
These short links are especially useful for:
Popular services like Shorten World, Bitly, TinyURL, and Rebrandly offer these features, but building your own solution gives you complete control and learning opportunities.
At the core of every URL shortener is a simple concept: mapping a short unique code to a long URL in a database. Here’s how it works:
abc123
).sho.rt/abc123
, the service looks up the code and redirects them to the original URL.Some shorteners also allow expiration dates, tracking click stats, and using custom aliases.
Python is a popular choice for developers due to:
Python makes it easy to prototype and scale your URL shortener from a personal tool to a production-ready service.
Before diving into code, let’s look at what you need:
Languages & Frameworks:
Database:
Libraries:
Development Tools:
Let’s build a simple URL shortener with Flask and SQLite.
mkdir python-url-shortener
cd python-url-shortener
python -m venv venv
source venv/bin/activate
pip install flask sqlalchemy
Create app.py
and initialize Flask:
from flask import Flask, request, redirect, jsonify
from flask_sqlalchemy import SQLAlchemy
import string, random
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///urls.db'
db = SQLAlchemy(app)
class URL(db.Model):
id = db.Column(db.Integer, primary_key=True)
original_url = db.Column(db.String(500), nullable=False)
short_code = db.Column(db.String(6), unique=True, nullable=False)
Create the database:
with app.app_context():
db.create_all()
def generate_short_code(length=6):
characters = string.ascii_letters + string.digits
while True:
code = ''.join(random.choices(characters, k=length))
if not URL.query.filter_by(short_code=code).first():
return code
@app.route('/shorten', methods=['POST'])
def shorten():
data = request.get_json()
original_url = data.get('url')
if not original_url:
return jsonify({'error': 'Missing URL'}), 400
code = generate_short_code()
new_url = URL(original_url=original_url, short_code=code)
db.session.add(new_url)
db.session.commit()
return jsonify({'short_url': request.host_url + code})
@app.route('/<short_code>')
def redirect_to_url(short_code):
url = URL.query.filter_by(short_code=short_code).first()
if url:
return redirect(url.original_url)
return jsonify({'error': 'URL not found'}), 404
Run the app:
if __name__ == '__main__':
app.run(debug=True)
Test the API using Postman:
POST to /shorten
with { "url": "https://example.com" }
Then visit the returned short URL.
If you're comfortable with Django, you can build a more feature-rich version using Django's ORM, templates, and admin interface.
Django advantages:
Flask advantages:
For a small-scale project or learning, Flask is recommended. For production or team-based work, Django is more robust.
Let users choose their short code:
@app.route('/custom', methods=['POST'])
def custom_shorten():
data = request.get_json()
original_url = data.get('url')
alias = data.get('alias')
if URL.query.filter_by(short_code=alias).first():
return jsonify({'error': 'Alias already taken'}), 400
new_url = URL(original_url=original_url, short_code=alias)
db.session.add(new_url)
db.session.commit()
return jsonify({'short_url': request.host_url + alias})
Add qrcode
library:
pip install qrcode[pil]
Generate and return a QR image:
import qrcode
from io import BytesIO
from flask import send_file
@app.route('/qr/<short_code>')
def generate_qr(short_code):
url = request.host_url + short_code
img = qrcode.make(url)
buf = BytesIO()
img.save(buf)
buf.seek(0)
return send_file(buf, mimetype='image/png')
To go live, consider the following steps:
Don’t forget to set up logging and backups for the database.
URL shortening might look simple on the surface, but it involves key web development concepts such as database design, HTTP routing, security, and API creation. Building a URL shortener in Python is an excellent way to practice these skills while creating a useful tool.
Whether you're a beginner learning Flask or a seasoned developer looking to extend it into a branded link management system, this project is scalable and rich in learning opportunities.
Key takeaways:
Now it’s your turn — start coding and create your own Python-powered short link platform today!