Simple URL Shortener using Python
URL shorteners are handy tools that take long URLs and convert them into short, easily shareable links. In this article, we’ll walk through the creation of a basic URL shortener using Python.
How It Works
- UrlShortener Class: We define a
UrlShortenerclass that includes methods for shortening and expanding URLs. - Shortening URLs: The
shorten_urlmethod takes an original URL, generates an MD5 hash of the URL, and uses the first 6 characters as the short URL. The mapping between short and original URLs is stored in a dictionary. - Expanding URLs: The
expand_urlmethod retrieves the original URL using the short URL from the dictionary.
Get Aarav Gupta’s stories in your inbox
Join Medium for free to get updates from this writer.
Now, let’s create a basic Python script for a URL shortener:
import hashlib
class UrlShortener:
def __init__(self):
self.url_mapping = {}
self.base_url = "http://short.url/"
def shorten_url(https://medium.com/self,%20original_url):
hash_value = hashlib.md5(original_url.encode()).hexdigest()[:6]
short_url = self.base_url + hash_value
self.url_mapping[short_url] = original_url
return short_url
def expand_url(https://medium.com/self,%20short_url):
original_url = self.url_mapping.get(short_url)
return original_url
#Example
url_shortener = UrlShortener()
original_url = input("enter url here: ")
short_url = url_shortener.shorten_url(https://medium.com/original_url)
print(f"Original URL: {original_url}")
print(f"Short URL: {short_url}")
expanded_url = url_shortener.expand_url(https://medium.com/short_url)
print(f"Expanded URL: {expanded_url}")Considerations
- This is a basic example. In a production environment, you would need to address concerns such as collisions, data persistence (e.g., using a database), and error handling.
- The choice of using MD5 for hashing is for simplicity. In practice, a more robust hashing algorithm like SHA2 and SHA3 and additional features would be recommended.
Feel free to modify and enhance the code based on your specific requirements.









