Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I expose data in a JSON format through a web service using Rails?

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

like image 950
Adrian Anttila Avatar asked Sep 11 '08 21:09

Adrian Anttila


2 Answers

Rails resource gives a RESTful interface for your model. Let's 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

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

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
like image 75
JasonOng Avatar answered Oct 21 '22 01:10

JasonOng


http://wiki.rubyonrails.org/rails/pages/HowtoGenerateJSON

like image 22
ceejayoz Avatar answered Oct 21 '22 00:10

ceejayoz