ApiBuilder is a Ruby on Rails template engine that allows for multiple formats being laid out in a single specification, currently XML and JSON.
In your Gemfile:
gem 'api_builder'
And run bundle install
.
In app/views/api/users/index.apibuilder:
array :users do @users.each do |user| element :user do id @user.id name @user.name end end end
Returns:
[ { "id": 1234, "name": "Peter Jackson" }, { "id": 1235, "name": "Marilyn Monroe" } ]
And the equivalent XML.
In app/views/api/users/show.apibuilder:
element :user do id @user.id name @user.name address do street @user.street city @user.city end array :interests do @user.interests.each do |interest| element :interest => interest.name end end end
Returns:
{ "id": 1234, "name": "Peter Jackson", "address": { "street": "123 High Way", "city": "Gotham City" }, "interests": [ "Movies", "Computers", "Internet" ] }
And the equivalent XML.
You can then call your API like this:
http://example.com/api/users?format=json
or
http://example.com/api/users?format=xml
and so on.
Here’s some more examples to get you started.
element :test => "value"
element :element => "value"
element :article => Article.first
element :articles => Article.all
ApiBuilder supports both JSON and XML.
ApiBuilder supports JSONP requests. Just call your URL with a callback parameter, e.g.:
http://example.com/api/users?format=json&callback=myCallback
Questions and suggestions are welcome at lassebunk@gmail.com. My blog is at lassebunk.dk.
Copyright © 2011 Lasse Bunk, released under the MIT license