LoginSignup
10
8

More than 3 years have passed since last update.

【Ruby】OAuth認証を使ってWeb APIへPOST HTTPリクエストの送信

Last updated at Posted at 2020-05-18

RubyでHTTPリクエストを送信する

今回は一番ベーシックなnet/httpを使用したサンプルを挙げるが、RubyのHTTPクライアントは複数ある。

サンプルコード

リクエストパラメータについて、
GETの場合はパラメータをクエリストリングに含めるが、
POSTの場合はリクエストボディに含めるという点にてちょっとハマった。

後で書き直す。

require 'uri'
require 'net/http'
require 'openssl'
require 'base64'

## 1. Oauth認証によるアクセストークンの取得
# client_idと client_secretを使用
client_id = ENV['API_CLIENT_ID']
client_secret = ENV['API_CLIENT_SECRET']
credential = Base64.strict_encode64(client_id + ':' + client_secret)
uri = URI.parse('https://example.oauth2/token')

# アクセストークンを取得するHTTPリクエストの作成
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
# 以下は使用するWeb APIの仕様により異なる。
request_header = {
  'Authorization': "Basic #{credential}",
  'Content-Type': 'application/x-www-form-urlencoded'
}
request = Net::HTTP::Post.new(uri.request_uri, request_header)
request.body = 'grant_type=client_credentials'

# リクエストの送信・レスポンスからアクセストークンの取得
response = https.request(request)
response_body = JSON.parse(response.body)
access_token = response_body['access_token']

## 2. Web APIへHTTPリクエストの送信
# アクセストークンを使用するHTTPリクエストの作成
endpoint_uri = URI.parse('https://example.api.com' + '/v1/hoge/huga')
https = Net::HTTP.new(endpoint_uri.host, endpoint_uri.port)
https.use_ssl = true
# 以下は使用するWeb APIの仕様により異なる。
request_header = {
  'Authorization': "Bearer #{access_token}",
  'Content-Type': 'application/x-www-form-urlencoded',
  'Accept': 'application/json'
}
request = Net::HTTP::Post.new(endpoint_uri.request_uri, request_header)
data = { api_key: "abcd1234", name: "test", email: "example@foo.com" }
request.body = URI.encode_www_form(data)

# リクエストの送信・レスポンスの取得
response = https.request(request)

参考

利用するWeb APIの仕様やサンプルコードがあればそれもちゃんと読みましょう。

net/http以外のRubyでHTTPを扱うライブラリ

faraday

oauth2

10
8
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
10
8