The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Build a dynamic link shortener

Building a dynamic link shortener requires a combination of backend logic to handle the shortening of URLs and a frontend interface for users to interact with. Here’s a basic guide on how you can build one using Python (Flask) for the backend and a simple HTML front-end. You can use any database, but for simplicity, I’ll demonstrate this with SQLite.

1. Backend: Python with Flask

First, you need to install the necessary packages. You can do this via pip:

bash
pip install Flask Flask-SQLAlchemy

2. Database Setup

We’ll use SQLite to store the original URLs and their corresponding short URLs.

python
from flask import Flask, request, redirect, render_template from flask_sqlalchemy import SQLAlchemy import hashlib import random import string app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///links.db' db = SQLAlchemy(app) # Create a model for storing the links class Link(db.Model): id = db.Column(db.Integer, primary_key=True) original_url = db.Column(db.String(500), nullable=False) short_url = db.Column(db.String(50), unique=True, nullable=False) def __repr__(self): return f"<Link {self.original_url} -> {self.short_url}>" # Create the database tables with app.app_context(): db.create_all()

3. Shortening Logic

The core part of a link shortener is generating a unique short link. Here, we’ll use a combination of random letters and a hash of the original URL.

python
def generate_short_url(): characters = string.ascii_letters + string.digits short_url = ''.join(random.choice(characters) for _ in range(6)) # 6 chars long return short_url def save_link(original_url): short_url = generate_short_url() new_link = Link(original_url=original_url, short_url=short_url) db.session.add(new_link) db.session.commit() return short_url

4. Handling Requests

Now let’s add the routes that will handle the creation and redirection of shortened links.

python
@app.route('/') def index(): return render_template('index.html') @app.route('/shorten', methods=['POST']) def shorten_link(): original_url = request.form['url'] short_url = save_link(original_url) return f"Shortened URL is: <a href='/{short_url}'>/{short_url}</a>" @app.route('/<short_url>') def redirect_to_url(short_url): link = Link.query.filter_by(short_url=short_url).first() if link: return redirect(link.original_url) return "URL not found", 404 if __name__ == '__main__': app.run(debug=True)

5. Frontend: Simple HTML Form

Create a simple templates/index.html file to allow users to input their URLs.

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Link Shortener</title> </head> <body> <h1>Link Shortener</h1> <form action="/shorten" method="POST"> <label for="url">Enter URL:</label> <input type="text" id="url" name="url" required> <button type="submit">Shorten</button> </form> </body> </html>

6. How It Works

  • The user enters a URL into the form on the homepage.

  • When the form is submitted, the backend generates a unique short URL and saves the mapping in the database.

  • The user is shown a shortened link (e.g., /abc123).

  • If the user visits /abc123, they are redirected to the original URL.

7. Running the Application

To run the application, just execute the following:

bash
python app.py

Visit http://127.0.0.1:5000 in your browser, and you can now use the link shortener!

Enhancements

  1. Customization: You could allow users to create custom short links instead of random ones.

  2. Analytics: Track the number of times a short link has been clicked.

  3. Expiration: Set expiration times for short links.

  4. Security: Add validation, rate limiting, and prevent malicious URL submissions.

That’s a basic dynamic link shortener! You can extend and improve this by adding user authentication, link expiration, and analytics features.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About