2021-09-15 Ruby HTTP Client、Faradayを使ってみる
Authentication
faraday/authentication.md at main · lostisland/faraday
Faraday.new(...) do |conn|
conn.request :authorization, 'Bearer', 'authentication-token'
# or
# conn.request :authorization, 'Bearer', -> { MyAuthStorage.get_auth_token }
end
Faraday.new(...) do |conn|
conn.request :authorization, :basic, 'username', 'password'
end
How to access the page protected by basic auth using Faraday? - Stack Overflow
connection = Faraday.new(url: url) do |conn|
conn.basic_auth(username, password)
end
👆これは Deprecated な書き方なので注意⚠
WARNING: `Faraday::Connection#basic_auth` is deprecated; it will be removed in version 2.0.
While initializing your connection, use `#request(:basic_auth, ...)` instead.
See https://lostisland.github.io/faraday/middleware/authentication for more usage info.
Twitter認証
Ruby: Faraday を使って HTTP リクエストを送信する - Sarabande.jp
require 'faraday'
require 'faraday_middleware'
require 'base64'
require 'uri'
key = 'xxxxxxx'
secret = 'xxxxxxx'
basic_token = Base64.strict_encode64(URI.encode(key) + ':' + URI.encode(secret))
client = Faraday.new 'https://api.twitter.com' do |b|
b.request :url_encoded
b.response :json, :content_type => /\bjson$/
b.adapter Faraday.default_adapter
end
client.authorization :Basic, basic_token
res = client.post 'oauth2/token', { :grant_type => 'client_credentials' }
bearer_token = res.body['access_token']
screen_name = 'sarabandejp'
client.authorization :Bearer, bearer_token
res = client.get '1.1/statuses/user_timeline.json?count=3&screen_name=' + screen_name
puts res.body[0]['text']
Simple get & post
require "faraday"
res = Faraday.get "http://httpbin.org/get", {a: "hoge"}
res = Faraday.post "http://httpbin.org/post", {a: "hoge"}
p res.status # => 200
p res.success? # => true
res.headers.each do |k, v|
puts "#{k}: #{v}"
end
puts res.body
conn = Faraday.new(:url => 'http://sushi.com') do |faraday|
faraday.request :url_encoded # form-encode POST params
faraday.response :logger # log requests to STDOUT
faraday.adapter Faraday.default_adapter # make requests with Net::HTTP
end
conn.post do |req|
req.url '/nigiri'
req.headers['Content-Type'] = 'application/json'
req.body = '{ "name": "Unagi" }'
end
## Per-request options ##
conn.get do |req|
req.url '/search'
req.options.timeout = 5 # open/read timeout in seconds
req.options.open_timeout = 2 # connection open timeout in seconds
end
Request を組み立てる
# コネクション生成時にミドルウェアをセット
connection = Faraday.new("http://example.com") do |builder|
builder.request :url_encoded # リクエストパラメータをURLエンコードする
builder.response :logger # リクエスト・レスポンスの内容を標準出力に出力する
builder.adapter :net_http # net/httpをアダプタに使う
end
# GETリクエスト
connection.get("/cats")
faraday のコード
faraday/faraday.rb at main · lostisland/faraday