Rails + Grape + Swaggerで簡単APIドキュメント
Grape + SwaggerでAPI実装からドキュメント作成まで簡単にできてしまいます!
画面イメージ
準備
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
へアクセスすると冒頭の画面が表示されます
サンプル
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
へアクセスすると冒頭の画面が表示されます
サンプル
bundle install
, rails s
してlocalhost:3000/docs
へアクセスすると冒頭の画面が表示されますAuthor And Source
この問題について(Rails + Grape + Swaggerで簡単APIドキュメント), 我々は、より多くの情報をここで見つけました https://qiita.com/rneuo/items/cd96694ee0f91feda50f著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .