6
5

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.

Rubyでhttps・Basic認証・GET/POST・JSONなWeb APIを呼ぶ

Last updated at Posted at 2016-12-06

Ruby 2.3.3で
(net/httpsは「このライブラリは Ruby 1.9.2 で net/http にマージされました。 そちらを使ってください。」になっていた)

require 'net/http'
require 'uri'
require 'json'

# get access_token
# (https GET with basic auth)
uri = URI('https://~')
req = Net::HTTP::Get.new(uri)
req.basic_auth('user', 'password')
res = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') { |http|
  http.request(req)
}
if res.is_a?(Net::HTTPSuccess)
  access_token = JSON.parse(res.body)['access_token']
else
  abort "get access_token failed: body=" + res.body
end

# call api
# (https POST with access_token)
post_body_hash = {  }
post_body_json = JSON.pretty_generate(post_body_hash)
uri = URI('https://~')
req = Net::HTTP::Post.new(uri)
req['Content-Type'] = req['Accept'] = 'application/json'
req['Authorization'] = 'bearer ' + access_token
req.body = post_body_json
res = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') { |http|
  http.request(req)
}
if res.is_a?(Net::HTTPSuccess)
  puts JSON.pretty_generate(JSON.parse(res.body))
else
  abort "call api failed: body=" + res.body
end
6
5
1

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
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?