from flask import Flask, request, redirect, jsonify, abort
import re
app = Flask(__name__)
# In-memory storage for URL mappings (short_code -> long_url)
urls = {}
counter = 0
# Base62 characters for short code generation
BASE62_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
def encode_to_base62(num):
"""
Convert an integer to a Base62 string.
"""
if num == 0:
return '0'
short_code = ''
while num > 0:
short_code = BASE62_CHARS[num % 62] + short_code
num //= 62
return short_code
@app.route('/shorten', methods=['POST'])
def shorten_url():
"""
Shorten a long URL.
Expects JSON: {"url": "https://example.com"}
Returns: {"short_url": "http://localhost:5000/abc123"}
"""
data = request.get_json()
long_url = data.get('url') if data else None
if not long_url:
return jsonify({'error': 'URL is required'}), 400
# Basic URL validation (starts with http:// or https://)
if not re.match(r'^https?://', long_url):
return jsonify({'error': 'Invalid URL format. Must start with http:// or https://'}), 400
# Generate unique short code using incremental counter
global counter
counter += 1
short_code = encode_to_base62(counter)
# Store the mapping
urls[short_code] = long_url
# Generate the short URL (adjust domain/port as needed for production)
short_url = f"http://localhost:5000/{short_code}"
return jsonify({'short_url': short_url}), 201
@app.route('/<short_code>')
def redirect_to_long_url(short_code):
"""
Redirect from short code to the original long URL.
Returns 404 if short code not found.
"""
long_url = urls.get(short_code)
if not long_url:
abort(404)
return redirect(long_url, code=302)
@app.errorhandler(404)
def not_found(error):
return jsonify({'error': 'Short URL not found'}), 404
if __name__ == '__main__':
print("URL Shortener running on http://localhost:5000")
print("POST to /shorten with JSON: {'url': 'https://example.com'}")
print("Example: curl -X POST -H 'Content-Type: application/json' -d '{\"url\":\"https://google.com\"}' http://localhost:5000/shorten")
app.run(debug=True, host='0.0.0.0', port=5000)
How to Use:
-
Install Flask: pip install flask
-
Run the script: python url_shortener.py
-
Shorten a URL:
curl -X POST -H "Content-Type: application/json" \
-d '{"url": "https://www.google.com"}' \
http://localhost:5000/shorten
Response: {"short_url": "http://localhost:5000/1"}
-
Access short URL: Visit http://localhost:5000/1 in a browser (redirects to Google).
Features:
- Unique short codes: Generated via Base62 encoding of an incremental counter (e.g., 1 → "1", 62 → "10").
- Basic validation: Ensures URL starts with
http:// or https://.
- In-memory storage: Fast for demos (lost on restart). For production, use Redis/SQLite.
- RESTful API: POST
/shorten and GET /<short_code>.
- Error handling: 400 for invalid input, 404 for unknown shorts.
- CORS-free: Simple script, no browser restrictions needed.
Production Notes:
- Replace in-memory dict with a database (e.g., SQLite via SQLAlchemy).
- Use a custom domain (e.g.,
bit.ly).
- Add rate limiting, custom codes, analytics.
- Secure with HTTPS and input sanitization.