At Devoxx the other week I spoke about Clojure, and as an example looked at how it could be used to access the Google+ public data API. Because the Google+ APIs are part of the general Google APIs Discovery Service we looked at how to process and generate functions to call this library automatically (more on which in later blog posts). However, for use now the easiest way to access any Google API via Clojure is probably via the Java client libraries using the Java interop in Clojure.
There’s a complete example up on Github, and it is really easy to get started. I use Leiningen to handle dependencies (as everyone should!), and because this backs onto Maven it can just pick up the Google repo which contains builds of a variety of useful libs. The project.clj file looks like this:
In this case we’re bringing in 3 jars from the Java API library: the (ridiculously fast) Jackson JSON parser, the base API client library and the Google+ API service. This last part is what you would replace (or add to) to query any one of the 50+ APIs available through this service.
To actually access the service we need to setup some variables. The HTTP transport is used for fetching and Jackson for the JSON decoding. In our case we’re using Simple API Access rather than OAuth, so we just need to pass our api key from the API console to a new PlusRequestInitializer. If you’ve not seen the Clojure Java interop before it is very straightforward - a “.” at the end of the method name means call the constructor of a class with that name, and a “.” at the start of a function means call this method on the object that is passed as the first argument.
You can see we call the setPlusRequestInitializer method on the plus-builder object we create on the previous line.
Now, we just need to perform our API call:
This function is very simple. We’re using the threading macro just to make the chain of object calls a little more readable. First we call activities on the Plus object to retrieve the Activities object that represents available posts. We then prepare that by calling its search method and passing the supplied query string. Finally we call execute on the returned Search object, and assign the result object to “results”.
We then use Clojure’s map function which happily iterates over the result set returned by the getItems() method on the search result object. Each activity gets passed to the anonymous function defined there, which pulls out the title and URL into a straightforward list.
While its not the most idiomatic Clojure in the world, it is very easy to wrap the client libraries in some more familiar code, and get going with the APIs very quickly!