LoginSignup
10
11

More than 5 years have passed since last update.

railsでGrapeを使ってAPI作成、プラス例外処理

Last updated at Posted at 2016-05-06

Grapeとは

APIを簡単に作ることができるライブラリの一つです。

GrapeでAPIを作成

1. データベースにAPIで使用するデータを入れる。

今回使用するテーブル Prefecture

id name capital
1 北海道 札幌市
2 青森県 青森市
3 岩手県 盛岡市

2. routes.rbとapplication.rbを編集

routes.rb
Rails.application.routes.draw do
  mount API => "/"
end
application.rb
module GrapeSampleApi
  class Application < Rails::Application
    config.active_record.raise_in_transactional_callbacks = true
    config.autoload_paths += %W(#{config.root}/lib/api)#←追記
  end
end

3. grapeのベースを作成

全体のエラー処理もここに書ける。

api.rb
# lib/api/api.rb
# coding: utf-8
class API < Grape::API

  # APIアクセスに接頭語を不可
  # ex) http://localhost:3000/api
  prefix "api"

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

  # 未指定の場合にJSONで返すように変更(URLで指定可能)
  format :json

  # 例外ハンドル 404
  rescue_from ActiveRecord::RecordNotFound do |e|
    rack_response({ message: e.message, status: 404 }.to_json, 404)
  end

  # 例外ハンドル 400
  rescue_from Grape::Exceptions::ValidationErrors do |e|
    rack_response e.to_json, 400
  end

  # 例外ハンドル 500
 rescue_from :all do |e|
   if Rails.env.development?
     raise e
   else
     error_response(message: "Internal server error", status: 500)
   end
 end

  mount Prefectures_API
end

4. データのやり取りを行う部分を作成

prefectures.rb
# lib/api/prefectures.rb
# coding: utf-8
class Prefectures_API < Grape::API
  resource "prefectures" do

    # ex) http://localhost:3000/api/v1/books
    desc "returns all prefectures"
    get do
      Prefecture.all
    end

    desc "return a prefecture"
    params do
      requires :id, type: Integer, values: 0..47 #0~47までを許容する。
      # optional :prefecture, type: String
    end
    # http://localhost:3000/api/v1/books/{:id}
    get ':id' do
      Prefecture.find(params[:id])
    end
  end
end

レスポンス

result.json
[
 {
  "id":1,
  "name":"北海道",
  "capital":"札幌市"
 },
 {
  "id":2,
  "prefecture":"青森県",
  "capital":"青森市"
 },
 {
  "id":3,
  "prefecture":"岩手県",
  "capital":"盛岡市"
 }
]

最後に

サクッと簡単にAPIが作ることができました。

宣伝になりますが、場所で起こす目覚ましアプリMapMeをリリースしました。
その他、Netflixの映画レビューサイトWhatchaSeeもリリースしていますので、ぜひ使ってみてください!!

10
11
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
10
11