LoginSignup
2
2

More than 5 years have passed since last update.

rails grapeを使ったAPI作成

Last updated at Posted at 2019-02-25

grapeを使ってAPIを作成したので、備忘録として記事にする

環境

macbook pro
Majavo
rails 4.2.4
ruby 2.1.0

grepのinstall

Gemfileに以下を追加した後、bundle install

gem 'grape'

ディレクトリ構造

以下のようなディレクトリ構造にする
ディレクトリ構造がきちんとなっていないとうまくできないので
出来るだけ、このまま行った方が良いです。

app
├apis
│  ├api
│   ├──root.rb
│   └ver1
│    ├ Tests.rb
│    └ root.rb

Path等の設定

config/routes.rbに以下を追加

routes.rb
mount API::Root => '/'

config/application.rbに以下を追加

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

api/root.tbに以下を追加

api/root.rb
module API
    class Root < Grape::API
        #http://localhost:3000/api
        prefix 'api'
        format :json

        mount API::Ver1::Root
    end
end

api/ver1/root.rbに以下を追加

api/ver1/root.rb
module API
    module Ver1
        class Root < Grape::API
            #http://localhost:3000/api/ver1
            format :json

            mount API::Ver1::Tests
        end
    end
end

APIの作成

Tests.rb

module API
    module Ver1
        class Events < Grape::API
            resource :tests do

                #POST /api/tests
                desc 'create event'
                params do 
                    requires :Title,        type: String ,  desc:'into title'
                    requires :document,         type: String,   desc:'body'
                end


                post :create do
                    Event.create(
                        title: params[:title],
                        document: params[:body],

                        #返り値
                        present :hash_id ,hash_id
                    end


            end
        end
    end
end

まとめ

今回はPOSTのみですが、GETなどを送りたいのであれば公式で確認ください
https://github.com/ruby-grape/grape

2
2
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
2
2