Class: NPR::API::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/npr/api/client.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ Client


Argument is a hash of params to send to the API. See <www.npr.org/api/inputReference.php> for API documentation.

Example:

NPR::Client.new(apiKey: "YOUR_API_KEY", sort: "date descending")

Any parameters passed into this method will override the global configuration.



33
34
35
36
37
# File 'lib/npr/api/client.rb', line 33

def initialize(params={})
  @params = NPR.config.merge(params)
  @url    = @params.delete(:url) || NPR::Configuration::API_ROOT
  @apiKey = @params.delete(:apiKey)
end

Instance Attribute Details

#paramsObject

Returns the value of attribute params.



19
20
21
# File 'lib/npr/api/client.rb', line 19

def params
  @params
end

#urlObject

Returns the value of attribute url.



19
20
21
# File 'lib/npr/api/client.rb', line 19

def url
  @url
end

Instance Method Details

#query(params = {}) ⇒ Object


Send a query to the NPR API.

Accepts a hash of options which get passed directly to the API.

Any parameters passed directly into this method will override both the global configuration, as well as any parameters stored in this object’s Example:

client.query(sort: "date descending", requiredAssets: "image")

For now, this forced JSON output. TODO: Support more formats



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/npr/api/client.rb', line 57

def query(params={})
  path = params.delete(:path) || NPR::Configuration::API_QUERY_PATH

  response = connection.get do |request|
    request.url path
    request.headers['Content-Type'] = "application/json"

    request.params = @params.merge(params)
    request.params['output'] ||= "json"  # Only JSON is supported.
    request.params['apiKey'] ||= @apiKey
  end

  if response.success?
    NPR::API::Response.new(response)
  else
    raise NPR::APIError, "The API call failed. (Status: #{response.status})"
  end
end