-
Notifications
You must be signed in to change notification settings - Fork 68
Examples of the default response formats
fabrik42 edited this page Apr 24, 2011
·
9 revisions
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
{
"users": [
{
"last_name": "Skywalker",
"first_name": "Luke"
},
{
"last_name": "Solo",
"first_name": "Han"
},
{
"last_name": "Leia",
"first_name": "Princess"
}
]
}
{
"user": {
"last_name": "Skywalker",
"first_name": "Luke"
}
}
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.
mycallback({
"users": [
{
"last_name": "Skywalker",
"first_name": "Luke"
},
{
"last_name": "Solo",
"first_name": "Han"
},
{
"last_name": "Leia",
"first_name": "Princess"
}
]
},
200)
mycallback({"user":{"last_name":"Skywalker","first_name":"Luke"}}, 200)
<?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>
<?xml version="1.0" encoding="UTF-8"?>
<user>
<first-name>Luke</first-name>
<last-name>Skywalker</last-name>
</user>