RubyでシンプルにAPIリクエストを行うための備忘録
Ruby の net/https にて、簡単に API のリクエストをしたいと思ったとき、
書き方がいくつもあるようで… 私が一番気に入っているコードを以下にメモしておきます。
GETリクエストの例
#! /usr/bin/env ruby
#-*- coding: utf-8 -*-
require 'net/https'
require 'json'
uri = URI.parse "https://qiita.com/api/v2/..."
req = Net::HTTP.new(uri.host, uri.port)
req.use_ssl = true
res = req.get(uri.request_uri)
arr = JSON.parse(res.body)
リクエストヘッダーを追加する
#! /usr/bin/env ruby
#-*- coding: utf-8 -*-
require 'net/https'
require 'json'
uri = URI.parse "https://qiita.com/api/v2/..."
req = Net::HTTP.new(uri.host, uri.port)
req.use_ssl = true
res = req.get(uri.request_uri, {
"Accept-Language" => "ja",
"Content-Type" => "application/json"
})
arr = JSON.parse(res.body)
クエリ文字列を追加する
#! /usr/bin/env ruby
#-*- coding: utf-8 -*-
require 'net/https'
require 'json'
uri = URI.parse "https://qiita.com/api/v2/..."
uri.query = URI.encode_www_form({
"id" => "c686397e4a0f4f11683d"
})
req = Net::HTTP.new(uri.host, uri.port)
req.use_ssl = true
res = req.get(uri.request_uri)
arr = JSON.parse(res.body)
POSTリクエストの例
#! /usr/bin/env ruby
#-*- coding: utf-8 -*-
require 'net/https'
require 'json'
uri = URI.parse "https://qiita.com/api/v2/..."
req = Net::HTTP.new(uri.host, uri.port)
req.use_ssl = true
res = req.post(uri.request_uri, {
"rendered_body" => "<h1>Example</h1>",
"body" => "# Example"
}.to_json)
arr = JSON.parse(res.body)
リクエストヘッダーを追加する
#! /usr/bin/env ruby
#-*- coding: utf-8 -*-
require 'net/https'
require 'json'
uri = URI.parse "https://qiita.com/api/v2/..."
req = Net::HTTP.new(uri.host, uri.port)
req.use_ssl = true
res = req.post(uri.request_uri, {
"rendered_body" => "<h1>Example</h1>",
"body" => "# Example"
}.to_json, {
"Accept-Language" => "ja",
"Content-Type" => "application/json"
})
arr = JSON.parse(res.body)
クエリ文字列を追加する
#! /usr/bin/env ruby
#-*- coding: utf-8 -*-
require 'net/https'
require 'json'
uri = URI.parse "https://qiita.com/api/v2/..."
uri.query = URI.encode_www_form({
"id" => "c686397e4a0f4f11683d"
})
req = Net::HTTP.new(uri.host, uri.port)
req.use_ssl = true
res = req.post(uri.request_uri, {
"rendered_body" => "<h1>Example</h1>",
"body" => "# Example"
}.to_json)
arr = JSON.parse(res.body)