Skip to content

Examples of the default response formats

fabrik42 edited this page Apr 24, 2011 · 9 revisions

Examples of the default response formats

acts_as_api provides support for xml, json and json-p by out of the box.

Given we have a defined the following api template for a model called User:

class User < ActiveRecord::Base

  acts_as_api

  api_accessible :name_only do |template|
    template.add :first_name
    template.add :last_name
  end

end

Note: To learn how to generate this responses in your Controller have a look at http://fabrik42.github.com/acts_as_api/ to get started.

Line breaks in responses are added for better readability

JSON Responses

Index, e.g. /users.json

{
    "users": [
        {
            "last_name": "Skywalker",
            "first_name": "Luke"
        },
        {
            "last_name": "Solo",
            "first_name": "Han"
        },
        {
            "last_name": "Leia",
            "first_name": "Princess"
        }
    ]
}

Show, e.g. /user/1.json

{
    "user": {
        "last_name": "Skywalker",
        "first_name": "Luke"
    }
}

JSON-P Responses

JSON-P Responses are disabled by default, but can easily be enabled by using the optional config block when activating a model to act as api:

class User < ActiveRecord::Base

  acts_as_api do |config|
    config.allow_jsonp_callback = true
  end

end

Now when a param[:callback] is given, the JSON response will be automatically wrapped into a JavaScript function call named after the param.

Additionally, by default the HTTP status of the response will be passed as the second argument to the JavaScript function.

Index, e.g. /users.json?callback=mycallback

mycallback({
    "users": [
        {
            "last_name": "Skywalker",
            "first_name": "Luke"
        },
        {
            "last_name": "Solo",
            "first_name": "Han"
        },
        {
            "last_name": "Leia",
            "first_name": "Princess"
        }
    ]
},
200)

Show, e.g. /user/1.json?callback=mycallback

mycallback({"user":{"last_name":"Skywalker","first_name":"Luke"}}, 200)

XML Responses

Index, e.g. /users.xml

<?xml version="1.0" encoding="UTF-8"?>
<users type="array">
  <user>
    <first-name>Luke</first-name>
    <last-name>Skywalker</last-name>
  </user>
  <user>
    <first-name>Han</first-name>
    <last-name>Solo</last-name>
  </user>
  <user>
    <first-name>Princess</first-name>
    <last-name>Leia</last-name>
  </user>
</users>

Show, e.g. /user/1.xml

<?xml version="1.0" encoding="UTF-8"?>
<user>
  <first-name>Luke</first-name>
  <last-name>Skywalker</last-name>
</user>
Clone this wiki locally