DEV Community

petercour
petercour

Posted on

Short URLS from Python

Many times you'll have long URLs that need to go to another device. Like say you have a long url in one computer, but you want to open that on another computer or phone.

To solve that problem, you can use short urls, or an url shortener.
But, did you know you can do that from Python?

#!/usr/bin/python3
import urllib.request

def tiny_url(url):
    apiurl = "http://tinyurl.com/api-create.php?url="
    tinyurl = urllib.request.urlopen(apiurl + url).read()
    return tinyurl.decode("utf-8")

print(tiny_url('https://news.ycombinator.com/item?id=20342791'))

This will output a short url for "https://news.ycombinator.com/item?id=20342791".

You can turn this in a little command line app

./tinyurl.py https://duckduckgo.com

Like this:

#!/usr/bin/python3                                                                                                        
import urllib.request
import sys

def tiny_url(url):
    apiurl = "http://tinyurl.com/api-create.php?url="
    tinyurl = urllib.request.urlopen(apiurl + url).read()
    return tinyurl.decode("utf-8")

url = sys.argv[1]
print(url)
print(tiny_url(url))

Learn Python?

Top comments (0)