Sunday, August 12, 2012

ROR web services: XML and JSON

Ruby on Rails makes web services unfairly easy to build. It gives ROR programmers such an advantage - probably, Rails should be banned.

Here how we make a web service: (based on Simple web service API with Ruby on Rails)

Create a simple application:


rails new eventsservices
cd eventsservices
rails g scaffold event title:string time:datetime
rake db:migrate
rails s

Open http://localhost:3000/events/, click "New Event" and type in some data.



Interesting part is here: by default, ROR knows how to show data in html JSON:

  1.   # GET /events/1
  2.   # GET /events/1.json
  3.   def show
  4.     @event = Event.find(params[:id])
  5.     respond_to do |format|
  6.       format.html # show.html.erb
  7.       format.json { render json: @event }
  8.     end
  9.   end

Adding xml is easy:


  1.   # GET /events/1
  2.   # GET /events/1.json
  3.   # GET /events/1.xml  
  4.   def show
  5.     @event = Event.find(params[:id])
  6.     respond_to do |format|
  7.       format.html # show.html.erb
  8.       format.json { render json: @event }
  9.       format.xml { render xml: @event }      
  10.     end
  11.   end

Check it out:



A problem here is that this approach does not work with show fuction (ALL Events) in xml part ("Template is missing")

So, let's use a modern  respond_to/respond_with functions:

  1.   respond_to :html, :xml, :json
  2.   # GET /events
  3.   # GET /events.json
  4.   # GET /events.xml
  5.   def index
  6.     respond_with(@events = Event.all)
  7.   end
  8.  
  9.   # GET /events/1
  10.   # GET /events/1.json
  11.   # GET /events/1.xml  
  12.   def show
  13.     @event = Event.find(params[:id])
  14.     respond_with(@events = Event.all)
  15.   end

And here we are. Bingo!



...little bit more on json customization here.

No comments:

Post a Comment