#Ruby の Faraday とは？ get リクエストで https 接続してみる例

# Faraday って何よ

Ralsで使われているけど、ほとんど何してるか知らなかった。

ネットワーク接続まわりの何かだという漠然としたイメージだった。

HTTP クライアントだということさえ知らなかった。生きててごめんなさい。

>Simple, but flexible HTTP client library, with support for multiple backends.

[lostisland/faraday: Simple, but flexible HTTP client library, with support for multiple backends.](https://github.com/lostisland/faraday)

# インストール

```
gem install faraday
```

# get リクエストを送ってみる

https アクセスするにも1行で書ける。

```
Faraday.get('https://example.com')
```

これだけ。

あー、あの Rails でもよく見るやつだ！

(と思ったのだが、デフォルトではなくて利用しているgemのdependencyかもしれない)

![image](https://user-images.githubusercontent.com/13635059/68068979-11fd8c00-fd9e-11e9-8226-15beb5084008.png)

```rb
[13] pry(main)> Faraday::Connection.new(url: 'https://example.com').get
=> #<Faraday::Response:0x00007fe48b0bfb40
 @env=
  #<struct Faraday::Env
   method=:get,
   body=
    "<!doctype html>\n<html>\n<head>\n    <title>Example Domain</title>\n\n    <meta charset=\"utf-8\" />\n    <meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <style type=\"text/css\">\n    body {\n        background-color: #f0f0f2;\n        margin: 0;\n        padding: 0;\n        font-family: -apple-system, system-ui, BlinkMacSystemFont, \"Segoe UI\", \"Open Sans\", \"Helvetica Neue\", Helvetica, Arial, sans-serif;\n        \n    }\n    div {\n        width: 600px;\n        margin: 5em auto;\n        padding: 2em;\n        background-color: #fdfdff;\n        border-radius: 0.5em;\n        box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);\n    }\n    a:link, a:visited {\n        color: #38488f;\n        text-decoration: none;\n    }\n    @media (max-width: 700px) {\n        div {\n            margin: 0 auto;\n            width: auto;\n        }\n    }\n    </style>    \n</head>\n\n<body>\n<div>\n    <h1>Example Domain</h1>\n    <p>This domain is for use in illustrative examples in documents. You may use this\n    domain in literature without prior coordination or asking for permission.</p>\n    <p><a href=\"https://www.iana.org/domains/example\">More information...</a></p>\n</div>\n</body>\n</html>\n",
   url=#<URI::HTTPS https://example.com/>,
   request=
    #<struct Faraday::RequestOptions
     params_encoder=nil,
     proxy=nil,
     bind=nil,
     timeout=nil,
     open_timeout=nil,
     write_timeout=nil,
     boundary=nil,
     oauth=nil,
     context=nil>,
   request_headers={"User-Agent"=>"Faraday v0.17.0"},
   ssl=
    #<struct Faraday::SSLOptions
     verify=true,
     ca_file=nil,
     ca_path=nil,
     verify_mode=nil,
     cert_store=nil,
     client_cert=nil,
     client_key=nil,
     certificate=nil,
     private_key=nil,
     verify_depth=nil,
     version=nil,
     min_version=nil,
     max_version=nil>,
   parallel_manager=nil,
   params=nil,
   response=#<Faraday::Response:0x00007fe48b0bfb40 ...>,
   response_headers=
    {"cache-control"=>"max-age=604800",
     "content-type"=>"text/html; charset=UTF-8",
     "date"=>"Sat, 02 Nov 2019 09:25:33 GMT",
     "etag"=>"\"3147526947+gzip\"",
     "expires"=>"Sat, 09 Nov 2019 09:25:33 GMT",
     "last-modified"=>"Thu, 17 Oct 2019 07:18:26 GMT",
     "server"=>"ECS (sjc/4E44)",
     "vary"=>"Accept-Encoding",
     "x-cache"=>"HIT",
     "content-length"=>"648",
     "connection"=>"close"},
   status=200,
   reason_phrase="OK">,
 @on_complete_callbacks=[]>
```

# response 

返ってきた response に対して重宝するメソッドが生えている。

controller でいつもお世話になってます。

status / headers / body

```rb
response = Faraday.get('https://example.com')

response.status
response.headers
response.body
```

![image](https://user-images.githubusercontent.com/13635059/68069036-8afce380-fd9e-11e9-8357-93ae77c41319.png)


```rb
[22] pry(main)> response.status
=> 200
[23] pry(main)> response.headers
=> {"accept-ranges"=>"bytes",
 "cache-control"=>"max-age=604800",
 "content-type"=>"text/html; charset=UTF-8",
 "date"=>"Sat, 02 Nov 2019 09:26:32 GMT",
 "etag"=>"\"3147526947+gzip\"",
 "expires"=>"Sat, 09 Nov 2019 09:26:32 GMT",
 "last-modified"=>"Thu, 17 Oct 2019 07:18:26 GMT",
 "server"=>"ECS (sec/96ED)",
 "vary"=>"Accept-Encoding",
 "x-cache"=>"HIT",
 "content-length"=>"648",
 "connection"=>"close"}
[24] pry(main)> puts response.body
<!doctype html>
<html>
<head>
    <title>Example Domain</title>

    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <style type="text/css">
    body {
        background-color: #f0f0f2;
        margin: 0;
        padding: 0;
        font-family: -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;

    }
    div {
        width: 600px;
        margin: 5em auto;
        padding: 2em;
        background-color: #fdfdff;
        border-radius: 0.5em;
        box-shadow: 2px 3px 7px 2px rgba(0,0,0,0.02);
    }
    a:link, a:visited {
        color: #38488f;
        text-decoration: none;
    }
    @media (max-width: 700px) {
        div {
            margin: 0 auto;
            width: auto;
        }
    }
    </style>
</head>

<body>
<div>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents. You may use this
    domain in literature without prior coordination or asking for permission.</p>
    <p><a href="https://www.iana.org/domains/example">More information...</a></p>
</div>
</body>
</html>
=> nil
[25] pry(main)> 
```

# POST リクエストの例

良さ！

`Faraday.post "http://httpbin.org/post", {hey: 'You'}`

```rb
[34] pry(main)> Faraday.post "http://httpbin.org/post", {hey: 'You'}
=> #<Faraday::Response:0x00007fe489788528
 @env=
  #<struct Faraday::Env
   method=:post,
   body=
    "{\n  \"args\": {}, \n  \"data\": \"\", \n  \"files\": {}, \n  \"form\": {\n    \"hey\": \"You\"\n  }, \n  \"headers\": {\n    \"Accept\": \"*/*\", \n    \"Accept-Encoding\": \"gzip;q=1.0,deflate;q=0.6,identity;q=0.3\", \n    \"Content-Length\": \"7\", \n    \"Content-Type\": \"application/x-www-form-urlencoded\", \n    \"Host\": \"httpbin.org\", \n    \"User-Agent\": \"Faraday v0.17.0\"\n  }, \n  \"json\": null, \n  \"origin\": \"103.5.142.120, 103.5.142.120\", \n  \"url\": \"https://httpbin.org/post\"\n}\n",
   url=#<URI::HTTP http://httpbin.org/post>,
   request=
    #<struct Faraday::RequestOptions
     params_encoder=nil,
     proxy=nil,
     bind=nil,
     timeout=nil,
     open_timeout=nil,
     write_timeout=nil,
     boundary=nil,
     oauth=nil,
     context=nil>,
   request_headers={"User-Agent"=>"Faraday v0.17.0", "Content-Type"=>"application/x-www-form-urlencoded"},
   ssl=
    #<struct Faraday::SSLOptions
     verify=true,
     ca_file=nil,
     ca_path=nil,
     verify_mode=nil,
     cert_store=nil,
     client_cert=nil,
     client_key=nil,
     certificate=nil,
     private_key=nil,
     verify_depth=nil,
     version=nil,
     min_version=nil,
     max_version=nil>,
   parallel_manager=nil,
   params=nil,
   response=#<Faraday::Response:0x00007fe489788528 ...>,
   response_headers=
    {"access-control-allow-credentials"=>"true",
     "access-control-allow-origin"=>"*",
     "content-type"=>"application/json",
     "date"=>"Sat, 02 Nov 2019 09:35:17 GMT",
     "referrer-policy"=>"no-referrer-when-downgrade",
     "server"=>"nginx",
     "x-content-type-options"=>"nosniff",
     "x-frame-options"=>"DENY",
     "x-xss-protection"=>"1; mode=block",
     "content-length"=>"277",
     "connection"=>"Close"},
   status=200,
   reason_phrase="OK">,
 @on_complete_callbacks=[]>
```

# REf

[Ruby HTTPクライアントの比較表 - Qiita](https://qiita.com/aosho235/items/559603ef98587ae4cfc1)
[Ruby の HTTP クライアントライブラリ Faraday が便利そう](https://gist.github.com/mitukiii/2775321)

# Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/2655








<!-- Update From Qiita API -->

# チャットメンバー募集


何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ





# Twitter


https://twitter.com/YumaInaura


<!-- Update From Qiita API -->