REST Hacking

First off, many thank yous to Brian Del Vecchio for linking to MyNCRE from BostonWTF. It's an awesome idea and Brian's an awesome guy. Thanks! 

In other news, I spent much of today hacking on a REST XML API. The good news: respond_to is awesome, as is render's :xml argument and especially ActiveRecord::Base's to_xml method. The bad news: sending POST requests with the Accept header set to "application/xml" isn't as easy as it could be.

Render's :xml argument was rather undocumented, but it's similar to the :text argument. The difference is the headers it sends are more tailored towards XML instead of plain text or HTML.

ActiveRecord::Base's to_xml has the documented :exclude option but also has the undocumented :only option. That combined with :include and the (also undocumented) :root option makes to_xml way more powerful than it seems at first. Witness:

render :xml => user.to_xml(:root => 'user',
:only => [:id, :email, :name])


render :xml => user.houses.to_xml(:include => [:media],
:exclude => secrets)

So that's the server side. Invoking those functions isn't as easy or pretty; you need to use the Net::HTTP module to send a POST request and add the "application/xml" header necessary to invoke the respond_to XML section. This turns out to be:

res =,port).post(path, data,
{'Accept' => 'application/xml'})

Then you have to check the result to see if it's a failure:

if res.is_a?(Net::HTTPSuccess)

Then you have to parse the XML:'house').map do |house_xml|

Since I'm complaining about it, I suppose I should write a plugin or something. I'll start that Friday, I guess.



  1. Posted June 8, 2006 at 7:07 am | Permalink

    Last weekend I had some fun with REST and Rails and found this article pretty useful:


  2. Posted June 8, 2006 at 1:39 pm | Permalink

    Okay, I see. It’s a wrapper that dispatches on the HTTP method type? I think it does some route handling too.

    A feature I’d like is authentication handling. Before the REST API is released I need a way to keep track of who is using this and what they have access to. Maybe I’ll decide that’s too specialized and that a plugin can’t solve this for me.

One Trackback/Pingback

  1. […] As I assured in a prior post, I spent today hacking on a plugin to make it easier to consume XML REST APIs. The result is the ResponseFrom plugin. It's the opposite of this: […]

%d bloggers like this: