Design a URL Shortening Service

Design a URL Shortening Service

Overview

We’ll build a simple URL shortener backend using Python (Flask) to demonstrate key concepts:

  • Generate a short URL key.
  • Store mapping in a database (we’ll use an in-memory dictionary for simplicity).
  • Redirect short URLs to original URLs.
9574ac4c 5b29 4302 8fa1 f8e7b6ca02e7 Simply Creative Minds

Step 1: Setup

JavaScript
Step 1: Setup

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

app = Flask(__name__)

# In-memory store for URL mappings: short_key -> long_url
url_db = {}

# Characters used for short keys
CHARSET = string.ascii_letters + string.digits
KEY_LENGTH = 6  # short key length

Step 2: Generate a unique short key

JavaScript
def generate_short_key():
    while True:
        key = ''.join(random.choices(CHARSET, k=KEY_LENGTH))
        if key not in url_db:
            return key

Step 3: API to shorten URL

JavaScript
@app.route('/shorten', methods=['POST'])
def shorten_url():
    data = request.get_json()
    long_url = data.get('long_url')

    # Simple validation
    if not long_url:
        return jsonify({'error': 'Missing long_url'}), 400

    # Generate short key
    short_key = generate_short_key()

    # Store mapping
    url_db[short_key] = long_url

    short_url = request.host_url + short_key
    return jsonify({'short_url': short_url}), 201

Step 4: Redirect short URL

JavaScript
@app.route('/<short_key>')
def redirect_url(short_key):
    long_url = url_db.get(short_key)
    if long_url:
        return redirect(long_url)
    else:
        return jsonify({'error': 'URL not found'}), 404

Step 5: Run the app

JavaScript
if name == 'main':
app.run(debug=True)

How this works:

  • When you POST a JSON like { "long_url": "https://example.com" } to /shorten, the server generates a 6-character key and stores it.
  • It returns a shortened URL like http://localhost:5000/a1B2c3.
  • When you visit http://localhost:5000/a1B2c3, it redirects to https://example.com.
a44ce712 e1ea 4455 b624 21a0eee06fb7 Simply Creative Minds

Limitations & Improvements

  • This example uses an in-memory dictionary, so URLs are lost when server restarts.
  • Real systems use persistent databases like Redis, DynamoDB, or SQL.
  • Key collisions are handled by retrying key generation.
  • No rate limiting or authentication.
  • No analytics or custom aliases.
  • No input URL validation or security checks.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *