Open Library and the beauty of Python

I’m currently working on a books site, so I recently was in the need to interact with the Open Library’s APIs, specifically to retrieve a book’s cover based on its ISBN. The API puts a limit on how many cover requests an IP can do when looking by ISBN, but not if you look by the OLID (Open Library book id), so I decided to see how hard it was to get a book’s OLID once I got its ISBN.

It’s useful every once in a while to recall how hard it was to accomplish certain things on certain cluttered and rigid languages, and how easy it is when you can use something as powerful as Python1. Well, I ended up with something like:

import urllib2
import json

URL = 'http://openlibrary.org/api/books?bibkeys=ISBN:{isbn}&format=json&jscmd=data'

def get_olid(isbn):

    response = urllib2.urlopen(URL.format(isbn=isbn))
    js_dict = json.loads(response.read())
    key = 'ISBN:{isbn}'.format(isbn=isbn)
    if js_dict.has_key(key):
        return js_dict[key]['identifiers']['openlibrary'][0]

But the real beauty of Python this time was not the clearness or succinctness of the code, nor how useful the libraries were, but rather how easy it was to figure out how to use those libraries. Just checked the function signatures on the online documentation (I could have used the help function, but I like the docs better), and started to play with them on the shell until I got the result I expected. It even saved me the time to read thoroughly the OL reference, since I could see in the shell the contents of the response they are sending me on each call.

1. Yes, there are no silver bullets, but there are some real good bullets and some real bad bullets for each job, and I find Python to be a great general purpose bullet :P.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s