Reputation: 20815
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?
Upvotes: 6
Views: 1361
Reputation: 10135
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.
Upvotes: 21
Reputation: 17145
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.
Upvotes: 3