LoginSignup
1
1

More than 5 years have passed since last update.

Rails 5.2 Grapeを利用したAPI作成、Swaggerでの確認 続編

Last updated at Posted at 2019-01-27

メモ続編 もう少しAPIらしくしてみる

前回
JSONのヘッダに こんなのをつけてみる

result: true,
message: "取得しました",
config/initializers/locale.rb
Rails.application.config.i18n.default_locale = :ja
config/locales/api.yml
ja:
  api:
    success_message:
      get: 取得しました
      create: 作成しました
      update: 更新しました
      delete: 削除しました
app/views/api/v1/task_displays/index.jbuilder
json.result true
json.message I18n.t('api.success_message.get')
json.tasks @tasks do |task|
  json.(task, :id, :name, :description)
end

スクリーンショット 2019-01-26 22.13.11.png

エラー対応

  • エラー対応のためエラー用のモジュールを定義
app/api/versions/v1/api.rb
module Versions
  module V1
    class API < Grape::API
      version 'v1', using: :path
      format :json
      formatter :json, Grape::Formatter::Jbuilder
      prefix :api

      # エラー対応
      rescue_from :all, backtrace: true
      error_formatter :json, ::MediaSite::ErrorFormatter

      include ::Versions::V1::TaskDisplays

      # :nocov:
      if Rails.env.development? || Rails.env.staging?
        add_swagger_documentation add_version: true
      end
      # :nocov:
    end
  end
end
  • エラー発生時に共通で呼ばれるモジュール
app/api/media_site/error_formatter.rb
module MediaSite
  module ErrorFormatter
    # error!メソッド実行時にJSONを出力する
    # 5つのパラメーターが渡されるのでそれを元にエラー出力
    # @param [Object] message メッセージまたはメッセージ+エラーコードのHash
    # @param [Array] _backtrace backtrace
    # @param [Hash] _options options
    # @params [Symbol] _env env
    # @params [不明] _other
    # @return [String] JSON文字列
    def self.call(message, _backtrace, _options, _env)
      if message.is_a?(Hash)
        { result: false }.merge(message).to_json
      else
        { result: false, message: message }.to_json
      end
    end
  end
end

パラメーター追加

  • idを指定してタスクを取れるように
app/api/versions/v1/task_displays.rb
module Versions
  module V1
    module TaskDisplays
      extend ActiveSupport::Concern
      included do
        namespace :tasks do
          namespace :displays do
            desc 'タスク一覧を取得する'
            get '', jbuilder: 'v1/task_displays/index' do
              @tasks = Task.all
            end

            desc "個別タスクの取得"
            params do
              requires :id, type: Integer
            end
            # http://localhost:3000/api/1/task_displays/{:id}
            get ':id', jbuilder: 'v1/task_displays/detail' do
              @task = Task.find(params[:id])
            end

          end
        end
      end
    end
  end
end
app/views/api/v1/task_displays/detail.jbuilder
json.result true
json.message I18n.t('api.success_message.get')
json.task do
  json.(@task, :id, :name, :description)
end
  • 結果
    http://localhost:3000/api/v1/tasks/displays/1
    スクリーンショット 2019-01-27 1.08.41.png

  • swaggerにも自動で追加される
    スクリーンショット 2019-01-27 1.10.15.png

  • エラー発生時
    存在しないタスクのidを指定した場合
    「result: false」となり message にエラーメッセージが入る
    スクリーンショット 2019-01-27 10.44.16.png

https://github.com/katafuchix/api_sample

1
1
0

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
1
1