Add to your Gemfile:
gem 'grape', '0.6.1'
gem 'grape-entity', '0.3.0'
gem 'grape-swagger', '0.7.6', :github => 'd4be4st/grape-swagger'
gem 'swagger-ui_rails', '0.1.7'
add to application.css and application.js
require swagger-ui
create a api_docs view with:
= render 'swagger_ui/swagger_ui', discovery_url: '/path/to/swagger_doc'
add route to routes.rb
get 'api/docs' => 'api_docs#index'
please read grape documentation
module API
class Users < Grape::API
desc 'Get all users'
get :users do
users = User.all
end
desc 'Get one user'
get 'users/:id' do
User.find(params[:id])
end
desc 'Create user'
params do
group :user do
requires :username, type: String
requires :email, type: String
optional :password, type: String
end
end
post :user do
User.create(params[:user])
end
end
end
please read grape-swagger documentation
module API
class Root < Grape::API
prefix 'api'
version 'v1'
format :json
mount API::Users
add_swagger_documentation api_version: 'v1', hide_documentation_path: true, hide_format: true
end
end
mount API::Root => '/'
Because of the prefix and the version, api urls are:
GET /api/v1/swagger_doc
GET /api/v1/users
GET /api/v1/users/:id
POST /api/v1/user
Use grape-entities
module API
class UserEntity < Grape::Entity
expose :email
expose :username
end
class Users < Grape::API
desc 'Get all users'
get :users do
users = User.all
present users, with: Users::Entity
end
end
end
- Clone this repository
- run bundle
- start server
- open localhost:3000/api/docs