Help us understand the problem. What is going on with this article?

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

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のフォローいただけると励みになります!
他にも方法がありましたら、コメントお待ちしております。
宜しくお願いします〜

sakuraniumarete
Railsエンジニア36歳アラフォー/仮想通貨の確定申告サービス開発/既婚/双子の父/エンジニアの方と交流したい/乃木坂・日向坂46が好き/最近はVue.jsやDocker、Go、AWSに興味あり/TECH::EXPERT卒(45期)
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした