4 Line python-based URL shortener

4 Line python-based URL shortener

Let's build an URL shortener with just 4 lines of code. I'll keep it as simple as possible.


I was building a discord BOT that has the feature of sending top news article in a given hour, but the URLs were too long so it was looking bad in a discord chat. So I thought of making an shortener service based on tiny-url to beautify those long a** URLs.


  • contextlib for utilities for with-statement contexts,
  • and urllib module which are built-in. So nothing needed to be installed.


import contextlib 
from urllib.parse import urlencode
from urllib.request import urlopen 

def tinyURLOf(url):
    encoded_url = urlencode({'url': url})
    request_url = 'http://tinyurl.com/api-create.php?' + str(encoded_url)
    with contextlib.closing(urlopen(request_url)) as response:                       
        return response.read().decode('utf-8 ')

So now run the function tinyURLOf(url='YOUR_URL_HERE') to get the result back.