LoginSignup
14
14

More than 5 years have passed since last update.

Rails&grapeで簡単WebAPI

Last updated at Posted at 2014-07-24

http://intridea.github.io/grape/docs/index.html
の通りに書くとエラー起こしたので覚書。

grapeの使い方というよりは導入の仕方。詳しくはドキュメントかGithubのREADMEを読んでください。

結局GithubのREADMEで解決した。

grape

grapeを使うと、簡単にWebAPIを作ることができます。

インストール

gem install grape

or

Gemfileに
gem 'grape'
を書いて bundle install してください

本体

公式ページで書かれているものの簡易版

注意
ディレクトリやファイルの名前が違うと、
uninitialized constant Piyo (NameError)
になります
autoloadの命名規約に従ってるはず。

app/api/piyo/api.rb
module Piyo
  class API < Grape::API

    format :json

    resource :api do

      desc "Return piyo."
      get :piyo do
        "piyo" #とりあえずテキトーなものを返す
      end

      desc "twice echo."
      params do
        requires :str, type: String, desc: "twice str"
      end
      get :twice do
        params[:str] * 2
      end

    end
  end
end

Railsへの設定

config/application.rb
module Test
  class Application < Rails::Aplication

    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
Rails.application.routes.draw do
  mount Piyo::API => '/'
end

curlから呼んでみる

curl http://localhost:3000/api/piyo
piyo

curl http://localhost:3000/api/twice?str=hello
hellohello

参考にしたサイト

-H Content-Type:application/json -v https://github.com/intridea/grape

File: README — Documentation by YARD 0.8.3 http://intridea.github.io/grape/docs/index.html

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