LoginSignup
12
9

More than 5 years have passed since last update.

Grapeを使ってRESTfulAPIを簡単作成 その3 Grape::Swagger

Last updated at Posted at 2016-12-10

Grape::Swaggerとは

grape-swaggerを使うと、grapeで作成したAPIのドキュメントが自動で生成されるようになります。
GitHub: ruby-grape/grape-swagger

目次

1.Grapeを使ってRESTfulAPIを簡単作成 その1 Grape
2.Grapeを使ってRESTfulAPIを簡単作成 その2 Grape::Entity
3.Grapeを使ってRESTfulAPIを簡単作成 その3 Grape::Swagger

環境

  • rails 5.0.0.1
  • ruby 2.3.1

まずはgemをインストール

下記を追記

Gemfile
# api
gem 'grape'
gem 'grape-entity'
gem 'grape_logging'

group :development, :staging do
  gem 'grape-swagger'
  gem 'grape-swagger-rails'
  # markdown
  gem 'redcarpet'
  # highlight for markdown
  gem 'rouge'
end

bundle install

$ bundle install --path vendor/bundle

ルーティングの設定

ドキュメントのURLが下記になるように設定します。
http://localhost:3000/docs

config/routes.rb
Rails.application.routes.draw do
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html

  # app/api/api.rbをマウント
  mount API => '/'
+ mount GrapeSwaggerRails::Engine => '/docs' if defined? GrapeSwaggerRails
end

swaggerの設定ファイルを作成

config/initializers/grape_swagger_railis.rb
このファイルを下記の内容で作成してください。

config/initializers/grape_swagger_railis.rb
if defined? GrapeSwaggerRails
  # swaggerのタイトルに表示される
  GrapeSwaggerRails.options.app_name    = "SampleApi"
  # http://localhost:3000/api/v1/swagger_doc
  GrapeSwaggerRails.options.app_url     = "/api/"
  GrapeSwaggerRails.options.url         = "v1/swagger_doc"
end

resourcesの親クラスに追記

app/api/resources/v1/root.rb

app/api/resources/v1/root.rb
module Resources
  module V1
    class Root < Grape::API
      version 'v1'
      format :json
      content_type :json, 'application/json'

      # app/api/resources/v1/users.rbをマウント
      mount Resources::V1::Users

+     # swaggerの設定
+     if defined? GrapeSwaggerRails
+       add_swagger_documentation(
+         markdown: GrapeSwagger::Markdown::RedcarpetAdapter.new(render_options: { highlighter: :rouge }),
+         api_version: 'v1',
+         base_path: '',
+         hide_documentation_path: true,
+         hide_format: true)
+     end
    end
  end
end

webサーバーを再起動して表示確認

これでAPIのドキュメントが見れるようになります。

grapeで新たなエンドポイントを追加すれば、ドキュメントにも自動で追加されます。
http://localhost:3000/docs

参考

RailsのAPIをswaggerでドキュメント化してみる

12
9
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
12
9