DEV Community

petercour
petercour

Posted on

1 4

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?

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay