Skip to content

Instantly share code, notes, and snippets.

@ejamesc
Created June 23, 2011 12:01
Show Gist options
  • Save ejamesc/1042420 to your computer and use it in GitHub Desktop.
Save ejamesc/1042420 to your computer and use it in GitHub Desktop.
Generate bit.ly urls in Python
import urllib
try:
import json
except ImportError:
import simplejson as json
#Enter your bitly username and apikey here
BITLY_USER = 'xxxxxx'
BITLY_API = 'xxxxxxxxxxxxxxxxxxxxxxxxx'
def shorten(url):
long_url = urllib.urlencode(dict(longUrl=url))
login = urllib.urlencode(dict(login=BITLY_USER))
apiKey = urllib.urlencode(dict(apiKey=BITLY_API))
encodedurl="http://api.bit.ly/shorten?version=2.0.1&%s&%s&%s" % (long_url, login, apiKey)
strm = urllib.urlopen(encodedurl)
respond_dict = json.loads(strm.read())
strm.close()
short_url = respond_dict["results"][url]["shortUrl"]
return short_url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment