acts_as_apiMakes creating XML/JSON responses in Rails 3 easy and fun. |
|
---|---|
The built-in XML/JSON support of Rails is great but: You surely don’t want to expose your models always with all attributes. acts_as_api enriches the models and controllers of your app in a rails-like way so you can easily determine how your API responses should look like. |
|
Features
|
|
|
|
Rails 3.0.x Quickstart |
|
Add to gemfile |
gem 'acts_as_api' |
Update your bundle |
bundle install |
Setting up your Model |
|
Given you have a model |
|
Within your model: First you activate acts_as_api for your model by calling Then you define an api template to render the model with |
class User < ActiveRecord::Base
acts_as_api
api_accessible :name_only do |template|
template.add :first_name
template.add :last_name
end
end |
An API template with the name See below how to use it in the controller: |
|
Setting up your Controller |
|
Now you just have to exchange the |
class UsersController < ApplicationController
def index
@users = User.all |
Note that it’s wise to add a |
respond_to do |format|
format.xml { render_for_api :name_only, :xml => @users, :root => :users }
format.json { render_for_api :name_only, :json => @users, :root => :users }
end
end
def show
@user = User.find(params[:id])
respond_to do |format|
format.xml { render_for_api :name_only, :xml => @user }
format.json { render_for_api :name_only, :json => @user }
end
end
end |
That’s it! |
|
Try it. The JSON response of #show should now look like this: Other attributes of the model like |
{
"user": {
"first_name": "John",
"last_name": "Doe"
}
} |
|
|
But wait! … there’s moreOften the pure rendering of database values is just not enough, so acts_as_api provides you some tools to customize your API responses. |
|
What can I include in my responses?You can do basically anything:
You can find advanced examples in the Github Wiki |
|
|
|
Links
|
|