LoginSignup
1
3

More than 3 years have passed since last update.

Grape / Rails / Swagger UI でAPIサーバーを構築する①

Last updated at Posted at 2020-04-22

grapeとは

RESTful APIを簡単に作るためのDSL(ドメイン固有言語)です。

Ruby 2.4以降が必要です。gemをインストールするだけです。

※Usersモデル(name)が作成されているアプリがある前提で話を進めていきます。

1.インストール

gemをGemfileに追加します。

Gemfile
gem 'grape'

bundle install
で実行します

2.基本ディレクトリの作成

[アプリ名] $ mkdir app/api
[アプリ名] $ mkdir app/api/base
[アプリ名] $ mkdir app/api/v1

3.base/api.rb の作成とマウント /V1::Rootの作成とマウント

[アプリ名] $ touch app/api/base/api.rb
/api/base/api.rb
module Base
  class API < Grape::API
    mount V1::Root
  end
end
config/routes.rb
Rails.application.routes.draw do
  mount Base::API => '/'
end

4.Base::APIからマウントするためのrootファイルを作成

APIの実装は app/api/v1 ディレクトリ以下に置いていくことになる。
また、 V1::Root 内で、各APIをマウントするのを忘れないようにする。

/api/v1/root.rb
module V1
  class Root < Grape::API
    version :v1
    format :json

    mount V1::Users
  end
end

5.application.rbの編集

applicationクラス定義内に、以下を追加します。

config/application.rb
config.paths.add File.join("app", "api"), glob: File.join("**", "*.rb")
config.autoload_paths += Dir[Rails.root.join("app", "api", "*")]

6.APIの実装

※Usersモデル(nameなど)が作成されているアプリがある前提で話を進めていきます。

以下のように追加します。

/api/v1/users.rb
module V1
  class Users < Grape::API
    resources :users do
      desc 'returns all users'
      get '/' do
        @users = User.all 
      end

      desc 'returns an user'
      params do
        requires :id, type: Integer
      end
      get '/:id' do
        @user = User.find(params[:id])
      end

      desc 'Create an user'
      params do
        requires :name, type: String
      end
      post '/' do
        @user = User.create(name: params[:name])
      en d

      desc 'Delete an user'
      params do
        requires :id, type: Integer
      end
      delete '/:id' do
        @user = User.find(params[:id])
        @user.destroy
      end
    end
  end
end

アプリを起動しましょう。

$ curl http://localhost:3000/v1/users

すると

{
    "id": 61,
    "name": "中島 七海",
    "email": "sample-59@email.com"
  },
  {
    "id": 62,
    "name": "渡辺 結菜",
    "email": "sample-60@email.com"
  }

のように返って来るはずです!!!!!(model内容によって違います)

Grape / Rails / Swagger UI でAPIサーバーを構築する②

今回APIを作成できたので、次回はそのAPIをSwagger UIで
簡単に操作できるようにします。
https://qiita.com/tksh8/items/c3a80a7cdfbd5086403f

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