Class: Juicer::Client

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

Constant Summary collapse

BASE_PATH =
"http://data.bbc.co.uk/bbcrd-juicer"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(api_key) ⇒ Juicer::Client

Initialize HTTP client

Parameters:

  • api_key (String)

    the API key from Apigee.



24
25
26
# File 'lib/juicer/client.rb', line 24

def initialize(api_key)
  @api_key = api_key
end

Instance Attribute Details

#api_keyString (readonly)

Returns API key.

Returns:

  • (String)

    API key



17
18
19
# File 'lib/juicer/client.rb', line 17

def api_key
  @api_key
end

Instance Method Details

#api_url(path) ⇒ String (private)

Small helper method for sanitizing the path for request method.

Parameters:

  • path (String)

    a path to an endpoint.

Returns:

  • (String)

    sanitized and fully constructed endpoint URL.



60
61
62
63
64
# File 'lib/juicer/client.rb', line 60

def api_url(path)
  path.sub!(/^\/+/, '')
  path.sub!(/\/+$/, '')
  "#{BASE_PATH}/#{path}.json"
end

#request(method, path, query_params = {}, body = nil) ⇒ Hash+

Note:

Internal method, should not be used directly! See Juicer docs instead.

Note:

The Juicer API currently only supports :get and :post values for the method param.

Internal method for constructing API calls to the Juicer public facing API. Automatically handles the API key when provided.

Parameters:

  • method (Symbol)

    HTTP method.

  • path (String)

    an endpoint path.

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

    a hash of query parameters. List values are handled "correctly" in the sense that values of [Array] type produce key[]=foo&key[]=bar style values, suitable for Rails.

  • body (String) (defaults to: nil)

    body of the request. Makes sense for POST requests.

Returns:

  • (Hash, Array<Hash>)

    either a list of results or one result.



43
44
45
46
47
48
49
50
51
# File 'lib/juicer/client.rb', line 43

def request(method, path, query_params = {}, body = nil)
  req                         = HTTPI::Request.new
  req.url                     = api_url(path)
  req.query                   = { apikey: api_key }.merge(query_params)
  req.body                    = body if body
  req.headers["Accept"]       = "application/json"
  req.headers["Content-Type"] = "application/json"
  JSON.parse(HTTPI.request(method, req).body)
end