LoginSignup
140
138

More than 5 years have passed since last update.

Grape | API生成マイクロフレームワーク

Last updated at Posted at 2012-08-01

Grapeは、RubyでRESTライクなAPIを生成する為のマイクロフレームワークです。
Grape
photo by Anders Ljungberg

リソース

インストール

Gemfileに、grapeを追記する。

Gemfile
gem 'grape'

インストールする。

$ bundle install

初期設定

libディレクトリ配下に、API実装ファイルを新規作成します。

$ touch lib/api.rb

libディレクトリ配下を自動的に読み込むように設定します。

config/application.rb
# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += %W(#{config.root}/lib)

ルーティングに、API実装ファイルのマウントを追記します。

config/routes.rb
mount API => "/"

利用方法

基本的な、Grapeの利用方法は以下のようになります。
paramsというブロックにて、パラメータのバリデータチェックも可能です。

lib/api.rb
class API < Grape::API
  # APIアクセスに接頭辞を付加
  # ex) http://localhost:3000/api
  prefix "api"

  # APIアクセスにバージョン情報を付加
  # ex) http://localhost:3000/api/v1
  version 'v1', :using => :path

  resource "users" do
    # ex) http://localhost:3000/api/v1/users
    desc "returns all users"
    get do
      User.all
    end

    # ex) OK: http://localhost:3000/api/v1/users/1
    # ex) NG: http://localhost:3000/api/v1/users/a
    desc "return a user"
    params do
      requires :id, type: Integer
      optional :name, type: String
    end
    get ':id' do
      User.find(params[:id])
    end
  end
end

合わせて読みたい

140
138
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
140
138