33
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rails console から web api を気軽に叩けるようにする

Last updated at Posted at 2013-02-06

Railsで構築した API を気軽に叩こうにも、ユーザ認証や authenticity_token が必要だったりして(POSTの場合)いろいろ面倒なことがあります。

そこで、.irbrc に以下のような記述を追加して、rails console (irb) から気軽に API を叩けるようにしてみました。

.irbrc
class Object

  # login する
  def login
    @base_uri = "http://localhost:3000"
    @agent = Mechanize.new
    page = @agent.get("#{@base_uri}/users/sign_in")
    page.form["user[email]"] = "user@example.com"
    page.form["user[password]"] = "password"
    page = @agent.submit(page.form)
    @authenticity_token = page.form["authenticity_token"]
    # form が無い場合は以下のように meta タグから取得
    # @authenticity_token = page.at('meta[@name="csrf-token"]')[:content]
  end

  def get(url, params = {})
    page = @agent.get "#{@base_uri}#{url}", params
    pp JSON.parse(page.body) unless page.body.blank?
    nil
  end

  def post(url, params = {})
    params.merge!( :authenticity_token => @authenticity_token )
    page = @agent.post "#{@base_uri}#{url}", params
    pp JSON.parse(page.body) unless page.body.blank?
    nil
  end
end

使用例

上記のコードを書いておくと、以下のように簡単に api を叩くことができる。

webシステムにログインする

login

get リクエストを投げる

get "/entries", { :user => "hoge" }

post リクエストを投げる

post "/entries", { :user => "hoge", :body => "ほげほげ" }
33
32
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
33
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?