Ruby
Rails
api
JSON
RubyOnRails

gem 'httpclient' を使用して外部API呼び出し

More than 1 year has passed since last update.

準備

gem インストール

gem install httpclient

使い方

1.requireする

sample.rb
+ require 'httpclient'
+ require 'json'

2.urlとパラメータを指定

sample.rb
require 'httpclient'
require 'json'

+ uri = "http://XXXXXX/XXXXX"
+ params = {
+   paramsA: "XXXX",
+   paramsB: "XXXX"
+ }

3.リクエスト実行

sample.rb
require 'httpclient'
require 'json'

uri = "http://XXXXXX/XXXXX"
params = {
  paramsA: "XXXX",
  paramsB: "XXXX"
}

+ client = HTTPClient.new
+
+ request =  client.get(uri,params)

4.レスポンスをjsonでパース

sample.rb
require 'httpclient'
require 'json'

uri = "http://XXXXXX/XXXXX"
params = {
  paramsA: "XXXX",
  paramsB: "XXXX"
}

client = HTTPClient.new

request =  client.get(uri,params)
+ response = JSON.parse(request.body)

proxyを使用する場合

sample.rb
require 'httpclient'
require 'json'

uri = "http://XXXXXX/XXXXX"
params = {
  paramsA: "XXXX",
  paramsB: "XXXX"
}
+ proxy = "http://proxy.XXX.co.jp:8080"

- client = HTTPClient.new
+ client = HTTPClient.new(proxy)

request =  client.get(uri,params)
response = JSON.parse(request.body)

ドキュメント

http://www.rubydoc.info/gems/httpclient/HTTPClient