Grape を使って Rails アプリに Web API を組み込む

Rails アプリに Web API を追加したい。 Rails のコントローラーで実装してもいいんだけど、せっかくなんで、 Web API マイクロフレームワーク『Grape』を試してみた。

Gemfile に

gem "grape"

を追加して bundle install でインストール。

RAILS_ROOT/app/apiapi.rb を作成。 RAILS_ROOT/lib に置くか迷ったけど、モデル使うし、Web API もアプリの一部と考えているから app 下に置くことにした。

# coding: utf-8

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

  helpers do
    def entries
      Entry.order("created_at DESC")
    end
  end

  resource "entries" do
    desc "エントリの一覧を返す"
    params do
      optional :page, type: Integer, desc: "Page number."
    end
    get do
      entries.page(params[:page])
    end

    desc "エントリを1件返す"
    params do
      requires :id, type: Integer, desc: "Entry ID."
    end
    get ":id" do
      entries.find(params[:id])
    end
  end

  resource "categories" do
    desc "すべてのカテゴリを返す"
    params do
      optional :page, type: Integer, desc: "Page number."
    end
    get do
      entries.category_counts.page(params[:page])
    end

    desc "指定したカテゴリのエントリ一覧を返す"
    params do
      requires :name, type: String, desc: "Tag name."
      optional :page, type: Integer, desc: "Page number."
    end
    get ":name" do
      entries.tagged_with(params[:name], on: :categories).page(params[:page])
    end
  end
end

kaminari を使っているんで、ページネーションも対応してみた。

この API クラスを Rails に組み込む。 API クラスは Rack アプリなので、Rails にそのままマウントできる。

# routes.rb

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

  # ...省略...
end

これだけで、Rails に Web API を組み込むことができた。

Grape は、ある程度宣言的に記述できるので、ぱっと見で何をやる Web API なのか分かりやすい。 API クラスにまとまっているので、見通しも良い。

今回みたいにサクっとこしらえたいときにはもってこいで、 さすが Web API に特化したマイクロフレームワークなだけある。