Skip to content

lassebunk/api_builder

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

40 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

About

ApiBuilder is a Ruby on Rails template engine that allows for multiple formats being laid out in a single specification, currently XML and JSON.

If you only need JSON, I recommend the Jbuilder gem: github.com/rails/jbuilder

Installation

In your Gemfile:

gem 'api_builder'

And run bundle install.

Examples

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.

More examples

Here’s some more examples to get you started.

Root element

element :test => "value"

Element with reserved name

element :element => "value"

Model element

element :article => Article.first

Model array

element :articles => Article.all

Features

Multiple formats

ApiBuilder supports both JSON and XML.

JSONP requests (callback parameter)

ApiBuilder supports JSONP requests. Just call your URL with a callback parameter, e.g.:

http://example.com/api/users?format=json&callback=myCallback

Contributors

  • Lasse Bunk (creator)

  • Dennis Reimann

Support

Questions and suggestions are welcome at lassebunk@gmail.com. My blog is at lassebunk.dk.

Copyright © 2011 Lasse Bunk, released under the MIT license

About

Ruby on Rails template engine that allows for multiple formats being laid out in a single specification.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages