16
Jun 10

Grackwalla: Talking to the Gowalla API using grackle

A while back I wrote a Twitter API ruby library called grackle. It’s seen quite a bit of use and takes a very lightweight approach to talking to the Twitter API. In fact, the thing I really like about grackle is that it really doesn’t make many assumptions about the API it’s talking to – it just issues RESTful requests using a straightforward syntax. This works great for talking to Twitter and it means grackle can easily be setup to talk to other APIs that use standard RESTful approaches. I thought I’d demonstrate this by setting grackle up to talk to Gowalla’s API. So, here goes:

client = Grackle::Client.new(
  :headers=>{"Content-Type"=>"application/json",
    "Accept"=>"application/json"},
  :auth=>{:type=>:basic,:username=>'USERNAME',:password=>'PASSWORD'})
client.api_hosts[:gowalla] = 'api.gowalla.com'
client.api = :gowalla

So what did I do there? Well here are the key elements:

  • First off, I set the headers as required by Gowalla’s API. Basically I’m just telling Gowalla that I want JSON back (which grackle understands) and can convert into a usable object.
  • Second, I tell grackle to use HTTP basic authentication as required by Gowalla
  • The client.api_hosts line is a little bit more esoteric. Grackle keeps a list of named “hosts”. That’s a little bit of a misnomer, it’s really a prefix for each request grackle makes. In this case, I’m telling grackle about the api.gowalla.com host and then telling it to use the new named host called :gowalla for subsequent requests.

If you’re unfamiliar with how grackle works, take a look at the grackle README and all will be explained. (Now might be a good time to do that… go ahead, I’ll wait…) With that bit of setup above, it’s now trivial to do things like:

#GET /users/hayesdavis
user = client.users.hayesdavis?
puts "#{user.first_name} #{user.last_name} has #{user.stamps_count} stamps"
# Prints "Hayes Davis has 184 stamps"

#GET /users/hayesdavis/stamps?limit=20
client.users.hayesdavis.stamps? :limit=>20 

#GET /users/categories
client.categories? 

#GET /spots?lat=30.2697&lng=-97.7494&radius=50
client.spots? :lat=>30.2697, :lng=>-97.7494, :radius=>50

The return values of the above methods will contain things called “TwitterStructs” but, never fear, those actually work like Ruby OpenStructs and match the JSON object returned by Gowalla’s API.

So go out and Gowalla with grackle. If you’re interested in connecting to other RESTful APIs, you can follow a similar pattern to get going.

P.S. My sincerest apologies for introducing the word “grackwalla” into the world.