Viewed 4645 times

Is there an easy way to return data to web service clients in JSON using Rails?

5 answers given for "How do I expose data in a JSON format through a web service using Rails?"

Accepted Solution

Rails resource gives a RESTful interface for your model. Let's see.


class Contact < ActiveRecord::Base


map.resources :contacts


class ContactsController < ApplicationController
  def show
    @contact = Contact.find(params[:id]

    respond_to do |format|
      format.xml {render :xml => @contact}
      format.js  {render :json => @contact.json}

So this gives you an API interfaces without the need to define special methods to get the type of respond required


/contacts/1 # Responds with regular html page

/contacts/1.xml # Responds with xml output of Contact.find(1) and its attributes

/contacts/1.js # Responds with json output of Contact.find(1) and its attributes

Rails monkeypatches most things you'd care about to have a #to_json method.

Off the top of my head, you can do it for hashes, arrays, and ActiveRecord objects, which should cover about 95% of the use cases you might want. If you have your own custom objects, it's trivial to write your own to_json method for them, which can just jam data into a hash and then return the jsonized hash.

There is a plugin that does just this,

And from what I understand this functionality is already in Rails. But go see that blog post, there are code examples and explanations.

ActiveRecord also provides methods to interact with JSON. To create JSON out of an AR object, just call object.to_json. TO create an AR object out of JSON you should be able to create a new AR object and then call object.from_json.. as far as I understood, but this did not work for me.