LoginSignup
48
47

More than 5 years have passed since last update.

grapeメモ

Last updated at Posted at 2014-03-16

Ruby on RailsでAPI用のコントローラ実装が楽になるgrapeを使ってみた。
grapeのバージョンは0.6.1。

Railsにgrapeをインストール

gemを使ってインストール

Gemfileに

gem 'grape'

と追記して

$ bundle install

APIクラスの読み込み

あとで作成するAPIクラスのために読み込みを設定する。config/application.rbに下記を追加

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

module Sample
  class Application < Rails::Application

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

  end
end

ルーティング

config/routes.rbでルーティングの設定

mount API => '/'

Sample::Application.routes.draw do
  mount API => '/'
end

APIクラスの設置

app/apiディレクトリを作りその下にapi.rbを設置。

class API < Grape::API
  prefix 'api'
  version 'v1', using: :path
  format :json

  helpers do
    def dummy_name
      "dummy"
    end
    def err401
      error!('401 Unauthorized', 401) 
    end
  end

  resource :room do

    get :status do
      "room is good"
    end

    get :secret do
      err401
    end
  end
end

APIアクセスするURLを下記のようになるようにしている。

http://localhost/:3000/<#プレフィックス#>/<#バージョン#>/<#リソース#>/<#メソッド#>?<#パラメータ#>

その他

rake routeは下記のようになるのでよくあるControllerのルーティングとは違うことに注意。これで問題ない。

$ rake routes
Prefix Verb URI Pattern Controller#Action
api  / API

プライベートメソッド

helpersで行う。例

  helpers do
    def dummy_name
      "dummy"
    end
    def err401
      error!('401 Unauthorized', 401) 
    end
  end

バリデーション

desc "チェックイン用のAPI"
params do
  requires :twitter_name, type: String, desc: "TwitterName"
end
post 'checkin/' do
end

必須

requires <#シンボル#>

タイプ指定

requires <#シンボル#>, type: <#クラス#>
48
47
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
48
47