Class: Yt::Request

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

Overview

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 = {}) ⇒ Request

Initializes a Request object.

Parameters:

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

    the options for the request.

Options Hash (options):

  • :method (String, Symbol) — default: :get

    The HTTP method to use.

  • :expected_response (Class) — default: Net::HTTPSuccess

    The class of response that the request should obtain when run.

  • :response_format (String, Symbol) — default: :json

    The expected format of the response body. If passed, the response body will be parsed according to the format before being returned.

  • :host (String)

    The host component of the request URI.

  • :path (String)

    The path component of the request URI.

  • :params (Hash) — default: {}

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

  • :camelize_params (Hash) — default: true

    whether to transform each key of params into a camel-case symbol before sending the request. For instance, if set to true, the params 1, d_e: 2, ‘f’ => 3 would be sent as 1, dE: 2, f: 3.

  • :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.

  • :body (#size)

    The body component of the request.

  • :headers (Hash) — default: {}

    The headers component of the request.

  • :auth (#access_token, #refreshed_access_token?)

    The authentication object. If set, must respond to access_token and return the OAuth token to make an authenticated request, and must respond to refreshed_access_token? and return whether the access token can be refreshed if expired.



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/yt/request.rb', line 53

def initialize(options = {})
  @method = options.fetch :method, :get
  @expected_response = options.fetch :expected_response, Net::HTTPSuccess
  @response_format = options.fetch :response_format, :json
  @host = options[:host]
  @path = options[:path]
  @params = options.fetch :params, {}
  # Note: This is to be invoked by auth-only YouTube APIs.
  @params[:key] = options[:api_key] if options[:api_key]
  # Note: This is to be invoked by all YouTube API except Annotations,
  # Analyitics and Uploads
  camelize_keys! @params if options.fetch(:camelize_params, true)
  @request_format = options.fetch :request_format, :json
  @body = options[:body]
  @headers = options.fetch :headers, {}
  @auth = options[:auth]
end

Instance Method Details

#as_curlString

Returns the cURL version of the request, useful to re-run the request in a shell terminal.

Returns:

  • (String)

    the cURL version of the request.



91
92
93
94
95
96
97
98
# File 'lib/yt/request.rb', line 91

def as_curl
  'curl'.tap do |curl|
    curl <<  " -X #{http_request.method}"
    http_request.each_header{|k, v| curl << %Q{ -H "#{k}: #{v}"}}
    curl << %Q{ -d '#{http_request.body}'} if http_request.body
    curl << %Q{ "#{uri.to_s}"}
  end
end

#runNet::HTTPResponse

Sends the request and returns the response. If the request fails once for a temporary server error or an expired token, tries the request again before eventually raising an error.

Returns:

  • (Net::HTTPResponse)

    if the request succeeds and matches the expectations, the response with the body appropriately parsed.

Raises:

  • (Yt::RequestError)

    if the request fails or the response does not match the expectations.



78
79
80
81
82
83
84
85
86
# File 'lib/yt/request.rb', line 78

def run
  if matches_expectations?
    response.tap{parse_response!}
  elsif run_again?
    run
  else
    raise response_error, error_message.to_json
  end
end