2
0

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 3 years have passed since last update.

HTTP クライアントライブラリのgem「faraday」を使ってみた

Last updated at Posted at 2020-07-13

HTTP クライアントライブラリのgem「faraday」を使用したので、メモ。
例えばAPIで取得する際に、gemを使用しないと

url = URI("https://api.coingecko.com/api/v3/coins/bitcoin")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Get.new(url)
response = http.request(request)
puts response.read_body

上記くらいコードが必要だが、faradayを使用すると


res =  Faraday.get("https://api.coingecko.com/api/v3/coins/bitcoin")
puts res

上記で取得できる

初期設定

まずはGemfileに追加して、bundle install

gem 'faraday'

パラメータ指定


response = Faraday.get("https://api.coingecko.com/api/v3/coins/bitcoin/history", date: "08-09-2017")
body = JSON.parse(response.body)

コネクション


connect =  Faraday.new("https://api.coingecko.com")
response = connect.get do |req|
  req.url '/api/v3/coins/bitcoin'
  req.params[:date] = "08-09-2017"
  req.params[:tickers] = :true
end
body = JSON.parse(response.body)

リクエストヘッダ


connection = Faraday.new("https://rest.coinapi.io")
response = connection.get "/v1/exchangerate/BTC/USD" do |request|
  request.headers["X-CoinAPI-Key"] = "API Key"
end

他にもいろいろ試してみようと思います〜

参考

Faradayの使い方 59のレシピ

以上です。
いいねやQiitaやTwitterのフォローいただけると励みになります!
他にも方法がありましたら、コメントお待ちしております。
宜しくお願いします〜

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?