ScissorsA couple of years ago, I showed you how to start your own URL shortening website. Recently I was working on an automation project that posts URLs to Twitter and I needed to keep the length of the URLs as short as possible so that they would fit within Twitter’s 140 character limit. Since I was writing the automation project entirely in Python, I needed a way to create short URLs from Python as well. So, I decided to create a super simple Python script that would utilize my personal URL shortener by posting lengthy URLs to it and have their shortened versions returned which I could then post to Twitter in my automation project. Today, I want to share that code with you in case you ever find yourself wanting to do something similar.

The code is easy to use and easy to follow. Just make sure you use your own URL shortener web address as the code I am providing here does not include a real URL shortener web address (as you can see in the code below). Once you have your own URL shortener web address in place, all you have left to do is pass in the URL you want to shorten (denoted by “long_url”) and it will return a shorter version for you at the end. If desired, you can also set the “keyword” field in the “data” dict if you want to use a specific prefix in your shortened URL.

import urllib, json

form_url = 'http://[YOUR_URL_SHORTENER_WEB_ADDRESS]/index_ajax.php'
long_url = 'http://www.prodigyproductionsllc.com/articles/automation/create-short-urls-with-python-and-yourls/'

data = {
    'mode' : 'add',
    'keyword' : '',
    'url' : long_url
}

params = urllib.urlencode(data)
request = urllib.urlopen(form_url, params)
response = request.read()
json_data = json.loads(response)
print json_data['shorturl']

When you run the above code, it will pass your long URL to your URL shortener which will shorten it and return the shortened URL which will be printed to the console. You can then use this shortened URL for whatever you need. All you need to do is store the json_data[‘shorturl’] value in a variable of its own.

One cool thing about this code is that if you post a long URL that has already been posted in the past, it will not generate a new short URL, but will instead return the short URL of the original long URL. If you need to check if the URL has already been posted before, you can get that from the “message” field in the “json_data” output. You can also get a few other things from the “json_data” output such as “status”, “code”, and “statusCode”.

That’s it! You can now shorten URLs from Python.

Thank you for your interest in my site. If you find the information provided on this site useful, please consider making a donation to help continue development!

PayPal will open in a new tab.
$2.00
$5.00
Other

Related Posts

Tagged with:  

Leave a Reply