Last Updated: September 09, 2019
·
6.063K
· drieanto

Setting routes for Rails API

Set default routes.rb

LearningApi::Application.routes.draw do
.
.
.
end

Do isolate api controller under namespace, create folder api under app/controllers

mkdir app/controllers/api

Add namespace to routes.rb

LearningApi::Application.routes.draw do

   namespace :api do
      # list of resources
   end

end

Set spesfiy MIME type format we only accept JSON

LearningApi::Application.routes.draw do

   namespace :api, defaults: { format: :json } do
      # list of resources
   end

end

Now set api as subdomain, something like api.learning-api.dev

LearningApi::Application.routes.draw do

   namespace :api, defaults: { format: :json }, constraints: { subdomain: 'api' }, path: '/' do
      # list of resources
   end

end