Using Grape Entities
Using Grape Entities
Rails チュートリアルで作成したアプリに REST API を実装するシリーズ。
- Doorkeeper による OAuth2 認可
- Grape による REST API 実装
- Swagger(OpneAPI) を用いたドキュメンテーションの追加
と進めてきて、今回は Grape Entities を使ってドキュメント中のレスポンス定義を明記してみる。
インストール
Using Grape Entities に沿って進める。
Grape::Entity
の インストール と GrapeSwagger::Entity
の インストール
gem 'grape-entity' gem 'grape-swagger-entity'
$ bundle
実装
Grape::Entity
で、レスポンスを整形GrapeSwagger::Entity
で、ドキュメントの記載を整形
基本的にこうなる。
User API を実際に書き換えてみる。
今まではとりあえず以下のように User モデルの内容をそのまま返却していた。
module V1 class Users < Grape::API ・ ・ ・ resource :users do desc 'Return all users.' get do User.all end ・ ・ ・
実際のレスポンスはこんな感じ。
[ { "id": 1, "name": "Example User", "email": "example@railstutorial.org", "created_at": "2017-07-22T02:26:19.028Z", "updated_at": "2017-07-22T02:26:19.028Z", "password_digest": "hogehoge", "remember_digest": null, "admin": true, "activation_digest": "hogehoge", "activated": true, "activated_at": "2017-07-22T02:26:18.922Z", "reset_digest": null, "reset_sent_at": null }, ・ ・ ・ ]
もはや何でもありで User データモデルの内容を全て返却している状態。
これを、
- 自分が意図した属性のみ返却
- 返却される値の定義をドキュメンテーション
とするのが今回の目標。
まずは Entity の定義から。
今回は全属性のうち、
- id
- name
を返却するよう実装する。(特に意図はないけどそれぐらいで良さそう?)
created_at
も入れておけば「このユーザーはいつから利用を開始しているか」とか表示できてそれっぽいか。
まぁ必要になったら追加することにしよう。
app/api/v1/users.rb
に以下を追記。
module V1 module Entities class User < Grape::Entity expose :id, documentation: { type: 'integer', desc: 'User ID.', required: true } expose :name, documentation: { type: 'string', desc: 'User name.', required: true } expose :email, documentation: { type: 'string', desc: 'User email address', required: true } end end class Users < Grape::API ・ ・ ・
とりあえず型と詳細、optional かどうかの指定をセットしている。
(他にも設定できる内容はたくさんある。)
次に実際に処理を書き換える。
module V1 class Users < Grape::API ・ ・ ・ resource :users do desc 'Return all users.', entity: Entities::User get do user = User.all present user, with: Entities::User end ・ ・ ・
これだけ。
動かしてみる。
[ { "id": 1, "name": "Example User", "email": "example@railstutorial.org" }, ・ ・ ・ ]
うん、意図通り。
レスポンス例が表示できて、
各属性の詳細が表示できて、
irb で AccessToken 発行まで進めておけば、Try it out! ボタンも正常に動作する。
良い感じである。
その他
これで下地が全部整った感あるので、
- REST API 全体設計
- 実装
と進めていく。
microposts とか、followers とか? 全容はまだぼんやり。