Bitly Data API

Over my Christmas vacation I decided to take on a small programing challenge.  I had stumbled upon the Bitly api a few days earlier and noticed that it provides some information about location of links, etc. so I decided to give it a go!

After looking over the api and data returned, I decided that it would be cool to build a map that displays trending locations on Bitly.  My first task was to see if I could find a python api client library for bitly, since python was going to be my server language of choice.  After looking over the apis listed here, I found that all of the apis were centered mainly around shortening urls and I needed more than that! So I picked up my favorite python rest library (restlib) and started working. I only needed a few api calls, but I figured it would be nice to build a simple library out of it so that I could reuse it.

I started out by creating a Connection class that would contain all of the methods to connect to the api.
[python]
class Connection():
“””Class that represents a connection to the bitly api.”””
access_token=””
_baseUrl=””
def __init__(self,access_token):
“””Creates a connection object with the specified access_token. This token should come from an oauth2 process.”””
self.access_token = access_token
self._baseUrl = “https://api-ssl.bitly.com/v3/”
[/python]

This gives me a simple framework that I can use to create a “connection” to the api, and ask for specific information, without trying to track an access_token though different requests. My first method was to find “hot phrases” as defined by the bitly api /v3/realtime/hot_phrases. This returns a list of trending phrases right now, and the links that are connected to them.

[python]
def realtime_hot_phrases(self):
“””Lists the current realtime hot phrases.”””
url = self._fullUrl(“realtime/hot_phrases”)
params={“access_token”:self.access_token}
result = restclient.GET(url,params)
result = json.JSONDecoder().decode(result)
self._checkStatus(result)
return result[“data”][“phrases”]
[/python]

In order to make my life easier I created a couple of private helper methods to make my life easier. The first is, “_fullUrl”, it takes in the url component that this particular method uses, and returns the full url. This just makes it easier to manage the urls, and I didn’t have to duplicate string concatenation all over the code.

The second is, “_checkStatus”, this method automatically checks the result returned by the http call for any errors that may have been returned by the api.

[python]
def _checkStatus(self,results):
“””Checks the status of a return, and raises Exceptions as appropriate.”””
try:
if results.has_key(“status_code”):
if results[“status_code”] == 200:
return
else:
raise BitlyError(“Status Code is not 200 (%s) (%s)”%(str(results[“status_code”]),str(results[“status_txt”])))
else:
raise BitlyError(“No status code found.”)
except Exception as e:
raise e
[/python]

This function automatically looks for the status code attribute of the result object, if it exists, and it is 200 the function will just return. If the status code is not 200, the a BitlyError is raised with details about the status that was returned. One thing that would make the library a bit more usable would be to add more status code errors, and raise errors with more detailed information about what happened.

With that done, you can easily get the hot links from bitly like this:

[python]
bit = Connection(“”)
print bit.realtime_hot_phrases()
[/python]

I added a few more methods for things like:

  • link_countries – To get the countries that a link is related to
  • link_locations – To get locations (a bit more specific than country) that a link is being used from
  • link_history – Gets the current logged in user’s link history
  • realtime_bursting_phrases – Gets  a list of phrases that are bursting in popularity among links right now

You can download the library here if you want to try it out.

I will add another post later about the final product LinkMap!

Leave a Reply