How do I create a URL shortener?

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

How to Create a URL Shortener

Creating a URL shortener involves several steps, from designing the system architecture to implementing the actual code. Below is a comprehensive guide to building a URL shortener.

1. System Design

Before diving into the code, it's essential to design the system:

Requirements

  • Functional:
    • Generate a short URL for a given long URL.
    • Redirect to the original URL when the short URL is accessed.
  • Non-Functional:
    • High availability and scalability.
    • Low latency for URL redirection.
    • Unique short URLs.

Components

  • Frontend: For users to input URLs and receive short URLs.
  • Backend: To handle URL shortening and redirection.
  • Database: To store the mappings between short and long URLs.

Flow

  1. User submits a long URL to the frontend.
  2. The frontend sends the URL to the backend.
  3. The backend generates a unique short URL.
  4. The backend stores the mapping in the database.
  5. The short URL is returned to the user.
  6. When the short URL is accessed, the backend looks up the long URL and redirects the user.

2. Choosing the Tech Stack

  • Frontend: HTML/CSS, JavaScript (optional: a framework like React)
  • Backend: Node.js with Express.js or Python with Flask/Django
  • Database: NoSQL (e.g., MongoDB) for scalability or SQL (e.g., MySQL) for relational data
  • Others: URL encoding library, HTTP server

3. Implementing the Backend

Example with Python (Flask) and SQLite

Step 1: Setting Up the Environment

Install Flask and SQLite:

pip install Flask

Step 2: Create the Flask Application

Create a file named app.py:

from flask import Flask, request, redirect, jsonify import sqlite3 import string import random app = Flask(__name__) # Database setup conn = sqlite3.connect('url_shortener.db', check_same_thread=False) c = conn.cursor() c.execute('''CREATE TABLE IF NOT EXISTS urls (id INTEGER PRIMARY KEY, long_url TEXT, short_url TEXT)''') conn.commit() # Function to generate a short URL def generate_short_url(): characters = string.ascii_letters + string.digits short_url = ''.join(random.choice(characters) for _ in range(6)) return short_url @app.route('/shorten', methods=['POST']) def shorten_url(): long_url = request.json['long_url'] short_url = generate_short_url() # Check for uniqueness c.execute("SELECT * FROM urls WHERE short_url=?", (short_url,)) while c.fetchone(): short_url = generate_short_url() c.execute("INSERT INTO urls (long_url, short_url) VALUES (?, ?)", (long_url, short_url)) conn.commit() return jsonify({"short_url": short_url}) @app.route('/<short_url>') def redirect_url(short_url): c.execute("SELECT long_url FROM urls WHERE short_url=?", (short_url,)) result = c.fetchone() if result: return redirect(result[0]) else: return "URL not found", 404 if __name__ == '__main__': app.run(debug=True)

Step 3: Run the Flask Application

Run the Flask app:

python app.py

4. Implementing the Frontend

Create a simple HTML form to interact with your backend.

index.html:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>URL Shortener</title> </head> <body> <h1>URL Shortener</h1> <form id="urlForm"> <input type="text" id="longUrl" placeholder="Enter your URL"> <button type="submit">Shorten</button> </form> <p id="result"></p> <script> document.getElementById('urlForm').addEventListener('submit', async function(event) { event.preventDefault(); const longUrl = document.getElementById('longUrl').value; const response = await fetch('/shorten', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ long_url: longUrl }) }); const data = await response.json(); document.getElementById('result').innerText = `Short URL: ${window.location.href}${data.short_url}`; }); </script> </body> </html>

5. Enhancements

  • Validation: Add validation to check if the URL is in a valid format.
  • Analytics: Track how many times each short URL is accessed.
  • Custom Short URLs: Allow users to choose their custom short URLs if available.
  • Security: Implement rate limiting and CAPTCHA to prevent abuse.

Summary

Creating a URL shortener involves setting up a backend to handle URL mappings, a database to store these mappings, and a frontend for user interaction. By leveraging frameworks like Flask for the backend and simple HTML for the frontend, you can quickly set up a basic URL shortener. For more complex needs, you can scale this setup with a more robust database, additional features, and security measures. For more in-depth knowledge and practical examples on web development and system design, consider exploring Grokking the System Design Interview on DesignGurus.io.

TAGS
System Design Interview
CONTRIBUTOR
Design Gurus Team

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Does Netflix do a background check?
Which internship pays best?
Big O, how do you calculate/approximate it?
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Image
Grokking Data Structures & Algorithms for Coding Interviews
Image
Grokking Advanced Coding Patterns for Interviews
Image
One-Stop Portal For Tech Interviews.
Copyright © 2024 Designgurus, Inc. All rights reserved.