Class: Yt::HTTPRequest Private

Inherits:
Object
  • Object
show all
Defined in:
lib/yt/http_request.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

A wrapper around Net::HTTP to send HTTP requests to any web API and return their result or raise an error if the result is unexpected. The basic way to use Request is by calling run on an instance.

Examples:

List the most popular videos on YouTube.

host = ''www.googleapis.com'
path = '/youtube/v3/videos'
params = {chart: 'mostPopular', key: ENV['API_KEY'], part: 'snippet'}
response = Yt::Request.new(path: path, params: params).run
response.body['items'].map{|video| video['snippet']['title']}

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ HTTPRequest

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Initializes a Request object.

Parameters:

  • options (Hash) (defaults to: {})

    the options for the request.

Options Hash (options):

  • :method (Symbol) — default: :get

    The HTTP method to use.

  • :host (String)

    The host of the request URI.

  • :path (String)

    The path of the request URI.

  • :params (Hash) — default: {}

    The params to use as the query component of the request URI, for instance the Hash {a: 1, b: 2} corresponds to the query parameters “a=1&b=2”.

  • :headers (Hash) — default: {}

    The headers of the request.

  • :body (#size)

    The body of the request.

  • :request_format (Hash) — default: :json

    The format of the requesty body. If a request body is passed, it will be parsed according to this format before sending it in the request.

  • :error_message (Proc)

    The block that will be invoked when a request fails.



33
34
35
36
37
38
39
40
41
42
# File 'lib/yt/http_request.rb', line 33

def initialize(options = {})
  @method = options.fetch :method, :get
  @host = options.fetch :host, 'www.googleapis.com'
  @path = options[:path]
  @params = options.fetch :params, {}
  @headers = options.fetch :headers, {}
  @body = options[:body]
  @request_format = options.fetch :request_format, :json
  @error_message = options.fetch :error_message, ->(body) {"Error: #{body}"}
end

Instance Method Details

#runNet::HTTPResponse

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Sends the request and returns the response with the body parsed from JSON.

Returns:

  • (Net::HTTPResponse)

    if the request succeeds.

Raises:



47
48
49
50
51
52
53
54
55
# File 'lib/yt/http_request.rb', line 47

def run
  if response.is_a? Net::HTTPSuccess
    response.tap do
      parse_response!
    end
  else
    raise Yt::HTTPError.new(error_message, response: response)
  end
end