Skip to main content

Command Palette

Search for a command to run...

4 Line python-based URL shortener

Published
1 min read
4 Line python-based URL shortener
T

I go by theroyakash on the internet. I am a computer scientist, with research in high performance algorithms, data structures, distributed systems, and beyond. See my work searching google for theroyakash.

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

Inspiration

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.

Requirements

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

Code

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.