Introducing AutoApi
posted
Sunday, August 03 at 03:50AM
My friend Evan Long wrote a nifty little article on his blog called RESTful Python, which included some code to easily create APIs for RESTful web services. Not to be outdone, I wrote my own. Here's the example usage:
require 'lib/auto_api'
class TwitterClient < AutoApi::Base
authenticate "username", "password"
service_url "http://twitter.com/statuses/friends_timeline.{format}"
remote_method :friends_timeline, {:default_parameters => {:format => "json"}}
service_url "http://twitter.com/statuses/user_timeline.{format}"
remote_method :user_timeline, {:default_parameters => {:format => "json"}}
end
twitter_client = TwitterClient.new
twitter_client.friends_timeline(:format => "xml") # returns json for friends timeline
twitter_client.user_timeline # returns json for user
Alternate construction for the same API:
class AlternateTwitterClient < AutoApi::Base
service_url "http://twitter.com/statuses/{remote_method}.{format}"
remote_method :friends_timeline, {:default_parameters => {:format => "json", :remote_method => "friends_timeline"}}
remote_method :user_timeline, {:default_parameters => {:format => "json", :remote_method => "user_timeline"}}
end
alternate_twitter_client = AlternateTwitterClient.new
# You can authenticate on a per-instance basis as well
alternate_twitter_client.authenticate("username", "password")
alternate_twitter_client.friends_timeline
And here's a Pownce client
class PownceClient < AutoApi::Base
service_url "http://api.pownce.com/2.0/note_lists/{username}.{format}"
remote_method :pownce_note_list, {:default_parameters => {:format => "json"}, :required_parameters => [:username]}
end
pownce_client = PownceClient.new
pownce_client.pownce_note_list(:username => "sintaks") # returns my Pownce note list
I'll throw the code somewhere. Or maybe not. It was mostly an academic exercise for me. I doubt anyone would find it useful. =)
Evan's code is considerably cleaner, partially due to the fact that Python has built-in decorators. Mine are kinda... home-brewed.
Update: I guess it wouldn't be any fun if I didn't show me posting a status update:
class AlternateTwitterClient < AutoApi::Base
authenticate "username", "password"
service_url "http://twitter.com/statuses/{remote_method}.{format}"
remote_method :friends_timeline, {:default_parameters => {:format => "json", :remote_method => "friends_timeline"}}
remote_method :user_timeline, {:default_parameters => {:format => "json", :remote_method => "user_timeline"}}
remote_method :update_status, {:default_parameters => {:format => "json", :remote_method => "update"}, :required_parameters => [:status], :request_method => :post}
end
alternate_twitter_client = AlternateTwitterClient.new
alternate_twitter_client.update_status :status => "Testing AutoApi: http://heypanda.com/posts/44-Introducing-AutoApi"
# And you can view this update, which I actually made, here: http://twitter.com/sintaks/statuses/876233423