動作検証環境
- Rails 5.2.3
namespace + version を付ける。
-
app/controllers/api4ext/v1
等。
base_controller.rb
を作る。
-
ActionController::API
を継承する。
app/controllers/api4ext/v1/base_controller.rb
class Api4ext::BaseController < ActionController::API
rescue_from Exception, with: :error_500
rescue_from ActiveRecord::RecordNotFound, with: :error_404
before_action :authenticate
def authenticate
end
def error_500(e)
logger.error("#{e.message}\n#{params.to_unsafe_h}\n#{e.backtrace.join("\n")}")
# NOTE: Send an exception here to an external service as follows if needed.
# Raygun.track_exception(e, custom_data: {params: params.to_unsafe_h})
render json: {}, status: :internal_server_error
end
def error_404
render json: {}, status: :not_found
end
end
resource 単位で controller を分ける。
app/controllers/api4ext/v1/accounts_controller.rb
module Api4ext
module V1
class AccountsController < Api4ext::BaseController
def show
end
def create
end
end
end
end
routing
config/routes.rb
namespace :api4ext do
namespace :v1 do
resources :accounts, only: [:show, :create]
end
end