LoginSignup
13
13

More than 5 years have passed since last update.

Railsアプリからnet/httpsでリクエストを投げる

Last updated at Posted at 2018-01-29

環境

  • Ruby 2.5.0
  • Rails 5.1.4

ファイル構成

ModelからAPIにリクエストを投げて、データを取得するような構成にしました。

- app/
  |- controlers/
    |- xxx_controller.rb
  |- models/
    |- Api
      |- xxx.rb

モデルの実装

クラスメソッドfindは、headerとクエリパラメータを引数とします。

そしてエンドポイントに対して、headerとクエリパラメータを投げ、json形式でレスポンスを受け取ります。

xxx.rb
require 'net/https'
require 'uri'

class Api::Xxx

  class << self

    def find(header, params)
      res = self.fetch ('https://example,com',
                        header,
                        params)
      JSON.parse(res.body, symbolize_names: true)
    end

    def fetch(url, headers, params)
      uri = URI.parse url

      http = Net::HTTP.new uri.host, uri.port
      http.use_ssl = true if uri.scheme == 'https'

      req = Net::HTTP::Get.new uri.request_uri

      req["Content-Type"] = 'application/json'
      headers.each do |k,v|
        req[k] = v
      end
      req.body = params.to_json

      http.request req
    end
  end
end

コントローラの実装

headerとクエリパラメータを引数として、json形式で取得しています。

xxx_controller.rb

class XxxController < ApplicationController
  def hoge
    result = Api::Xxx.find(header, params)
    # (省略)
  end

  private
    def header
      { 'Accept-Language' => "ja" }
    end

    def params
      { 'hoge' => "test" }
    end

end

参考リンク

13
13
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
13
13