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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With