Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1 API Routes

I have a Rails 3.1 app that I want to create an API for. I want my urls to look something like:

www.example.com/controller/action // Normal Web requests
api.example.com/controller/action.json // API requests

The first one would be for normal requests and the other obviously for my API stuff. I would like both of these to map to the same controller/action.

How do I set up my application so that it only responds to HTML when on www and json, xml, etc when I am on the api subdomain?

like image 318
Kyle Decot Avatar asked Nov 15 '11 21:11

Kyle Decot


2 Answers

The easiest way (imo) would be, to use Rails 3 routing constraints. In config/routes.rb, use:

constraints :subdomain => 'www', :format => :html do
  # Routing for normal web requests
  match 'mycontroller/:action' => 'mycontroller#index'
  # ...
end

constraints :subdomain => 'api', :format => :json do
  # Routing for API requests
  match 'mycontroller/:action.:format' => 'mycontroller#index'
  # ...
end

You might also want to have a look into respond_with (and respond_to at class level), which makes it much easier to write controllers that respond to multiple formats than with traditional respond_to.

like image 152
Zargony Avatar answered Nov 17 '22 01:11

Zargony


Check #221 Subdomains in Rails 3 Rails Cast. For www you can put additional contstraint ":format => :html". Another solution would be using controller filter which checks request.subdomain and params[:format]. Then you don't need to duplicate routes.

like image 21
gertas Avatar answered Nov 17 '22 01:11

gertas