54
63

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で簡単APIドキュメント

Last updated at Posted at 2015-02-22

Grape + SwaggerでAPI実装からドキュメント作成まで簡単にできてしまいます!

画面イメージ

swagger.png

準備

rails new grape-swagger
cd grape-swagger
rails g scaffold user
rake db:migrate RAILS_ENV=development

設定

修正ファイル

Gemfile
gem 'grape', '~> 0.6.1'
gem 'grape-entity', '~> 0.4.0'
gem 'grape-swagger', '~> 0.7.2'
gem 'grape-swagger-rails'

ルーティング

config/routes.rb
mount API::Root => '/'
mount GrapeSwaggerRails::Engine => '/docs'

lib以下を自動で読み込み

config/application.rb
config.autoload_paths += %W(#{config.root}/lib)

新規作成ファイル

config/initializers/grape_swagger_rails.rb
GrapeSwaggerRails.options.url      = "swagger_doc.json"
GrapeSwaggerRails.options.app_name = 'GrapeSwagger'
GrapeSwaggerRails.options.app_url  = '/'
lib/api.rb
require 'grape'

module API
  class Root < Grape::API
    default_format :json

    mount API::Users => '/users'

    add_swagger_documentation(
      base_path: "/",
      hide_documentation_path: true
    )
  end
end
lib/api/users.rb
module API
  class Users < Grape::API

    desc 'get all users'
    get "all" do
      present User.all, with: API::Entities::User
    end

  end
end
lib/api/entities/user.rb
module API
  module Entities
    class User < Grape::Entity
      expose :name
    end
  end
end

サーバー起動

  • bundle install, rails sしてlocalhost:3000/docsへアクセスすると冒頭の画面が表示されます

サンプル

54
63
2

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
54
63

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?