Rails 3.1 API Routes

I have a Rails 3.1 application for which I want to create an API. I want my urls to look something like this:

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

The first will be for regular requests, and the other, obviously, for my API material. I would like both to map to the same controller / action.

How to configure my application so that it only responds to HTML, when to www and json, xml, etc., when I am in the api subdomain?

+6
source share
3 answers

The easiest way (imo) is to use the Rails 3 routing restrictions. 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 can also view respond_with (and reply_to at the class level), which makes it easier to write controllers that respond to several formats than with traditional response_to.

+21
source

Check out # 221 Subdomains in the Rails 3 Rails Cast. For www you can add an extra contstraint ": format =>: html". Another solution would be to use a controller filter that checks request.subdomain and params [: format]. Then you do not need to duplicate routes.

+3
source

Can subdomain-fu help?

0
source

Source: https://habr.com/ru/post/901567/


All Articles