How can I provide JSON data through a web service using Rails?

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

+6
json ruby-on-rails web-services
source share
5 answers

The Rails resource provides a RESTful interface for your model. We'll see.

Model

class Contact < ActiveRecord::Base ... end 

Routes

 map.resources :contacts 

Controller

 class ContactsController < ApplicationController ... def show @contact = Contact.find(params[:id] respond_to do |format| format.html format.xml {render :xml => @contact} format.js {render :json => @contact.json} end end ... end 

This way, it gives you APIs without having to define special methods to get the type of response you need.

Eg.

 /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 
+10
source share
+4
source share

Rails monkeypatches most of the things you would like to have #to_json .

At the top of my head, you can do this for hashes, arrays, and ActiveRecord objects, which should cover about 95% of possible use cases. If you have your own custom objects, it is trivial to write your own to_json method for them, which can simply brake the data into a hash and then return a jsonized hash.

+2
source share

There is a plugin that does just that, http://blog.labnotes.org/2007/12/11/json_request-handling-json-request-in-rails-20/

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

+1
source share

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

0
source share

All Articles