views:

34

answers:

2

Suppose I want to be able to view a list of products on my site by going to /product/list. Great. So this uses my 'list' view and outputs some HTML which my web browser will render.

But now suppose I want to provide a REST API to my client where they can get a list of their products. So I suppose I'd have them authenticate with oAuth and then they'd call /product/list which would return a JSON array of their products.

But like I said earlier, /product/list displays an HTML web page. So, I have a conflict.

What is normal practice as far as providing APIs in Rails? Should I have a subdirectory, 'api', in /app/controller, and another 'product' controller? So my client would go to /api/product/list to get a list of their products?

I'm a bit new to RoR, so I don't have the best grasp of the REST functionality yet, but hopefully my question makes sense.

+1  A: 

Using the respond_do it's actually quite easy: http://weblog.jamisbuck.org/2006/3/27/web-services-rails-style

Then they can just go to products/list/index.json and be good to go.

Jade Robbins
+2  A: 

Hi,

the common practice is to use respond_to method. You can have one controller to render HTML web page, JSON or XML response.

class StatesController < ApplicationController
  def index
    @states = State.get_states_by_country(params[:country_id])

    respond_to do |format|
        format.html
        format.json { render :json => { :prompt => t('address.select_state'),
                                        :states => @states.to_json(:only => [:id], :methods => [:name]) }}
        format.js
    end
  end
end
Voldy
Sick. Just sick. I'm using ExtJS, and I figured out that I can do this -- Ext.Ajax.defaultHeaders = { 'Accept': 'application/json' }; -- and then as long as I have a format.json in my "responds_to" block, Rails knows that requests to '/product/list' should return JSON data--I don't have to request '/product/list.json'. Just awesome.
Chad Johnson