Mixing server-rendering of pages with an API in Rails

This is the recommended way of serving API-endpoints in a regular Rails application. Note the {format:json} in the “api” section. Rails default is {format :html}

Also note that the same controller is serving both HTML and JSON, but the /api scope makes this easier to use.

Rails.application.routes.draw do
  
  resources :products
  
  scope "/api", defaults: {format: :json} do
    resources :products
  end
end

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.