Rails subdomain and namespace route

Ruby on Rails, Web Development, 2015-10-24 03:44:07 UTC

Currently, I am creating an API for one of my application. Instead of using a URL like https://domain.com/api/v1/path_names, I choose https://api.domain.com/v1/path_names. And today, I want to share my experience with you.

The first thing that needs to do is to group all the controller in a namespace. 

We can reate through commandline;

$ rails g controller Api::V1::PathNames

You will see Rails creating a controller file app/controllers/api/v1/path_names_controller.rb

Now, you can create route;

namespace :api do
  namespace :v1 do
    resources :path_names
  end
end

Now we have https://domain.com/api/v1/path_names 

The next thing to do is creating a subdomain route.

You can change to subdomain route;

namespace :api, :constraints => {:subdomain => "api"} do
  namespace :v1 do
resources :path_names   end end

Now, URL look like https://api.domain.com/api/v1/path_names

As We know, We have 2 API words. We need to change to https://api.comain.com/v1/path_names. You can change the code to this;

namespace :api, :path => "", :constraints => {:subdomain => "api"} do
  namespace :v1 do
resources :path_names   end end

Thats it! :)

 

 

 


Share: