LoginSignup
2

More than 3 years have passed since last update.

【Rails】REST APIを書く時のサンプル

Last updated at Posted at 2019-07-26

動作検証環境

  • 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

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2