1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Rails】grape-swagger-railsでドキュメント作成

Posted at

grape-swagger-railsというGemを使って、APIのドキュメントを作成します。
なお、grape Gemを使ってAPIを作っている前提。

Swaggerインストール

Gemfileに下記を追加

Gemfile
gem 'grape-swagger' # Grapeで定義したAPIをSwagger形式でドキュメント化する
gem 'grape-swagger-entity' # レスポンスモデルをSwaggerで見られる形式にするときに使う
gem 'grape-swagger-rails' # Rails用のSwaggerUI
gem 'grape-swagger-representable' # ResponseをEntityで定義した形式でドキュメントに表示するときに使う

bundle install 実行

$ bundle install

Route追記

config/routes.rb
Rails.application.routes.draw do
  mount GrapeSwaggerRails::Engine => '/swagger' # 追記
end

設定ファイル作成

config/initializers/swagger.rbを作成

config/initializers/swagger.rb
GrapeSwaggerRails.options.app_name = "SampleApi" # タイトル
GrapeSwaggerRails.options.app_url = 'http://localhost:3000'
GrapeSwaggerRails.options.url = '/api/v1/swagger_doc'

add_swagger_documentation追記

root.rb にadd_swagger_documentationメソッドを追記する。

api/v1/root.rb
class V1::Root < Grape::API
...
  add_swagger_documentation() # 追記
...
end

これで localhost:8080 にアクセスすると、Swaggerドキュメントが表示される。

Responseを表示させる

SwaggerドキュメントにはResponseが表示されていないので、表示されるようにAPIを編集する。
descの後に使用しているEntityを追記。

users.rb
    desc 'returns all users', success: V1::Entities::UsersEntity
    get '/' do
      users = User.all
      present users, with: V1::Entities::UsersEntity
    end

これで V1:Entities::UsersEntity に記述されているResponseがドキュメントに表示される。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?