Class: APICake::Base

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
lib/apicake/base.rb

Overview

To create your API wrapper, make a class that inherit from this class.

This class includes the HTTParty module, and the only requirement, is that you call base_uri to define the base URI of the API.

Example

class Client < APICake::Base
  base_uri: 'http://some.api.com/v3'
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_sym, *args) ⇒ Object

Any undefined method call will be delegated to the #get method.

Example

This:

client = Client.new
client.path 'optional_sub_path', optional_param: value, optional_param: value

Is equivalent to this:

client.get 'path/optional_sub_path', optional_param: value, optional_param: value


56
57
58
# File 'lib/apicake/base.rb', line 56

def method_missing(method_sym, *args)
  get "/#{method_sym}", *args
end

Instance Attribute Details

#last_payloadObject (readonly)

Holds the last Payload object that was obtained by the last call to #get, #get!, #get_csv or #save_csv

Example

client = Client.new
client.some_path, param: value
p client.last_payload
# => a Payload object


29
30
31
# File 'lib/apicake/base.rb', line 29

def last_payload
  @last_payload
end

#last_urlObject (readonly)

Holds the last URL that was downloaded by the last call to #get, #get!, #get_csv or #save_csv.

Example

client = Client.new
client.some_path, param: value
p client.last_url
# => "http://some.api.com/v3/some_path?param=value"


41
42
43
# File 'lib/apicake/base.rb', line 41

def last_url
  @last_url
end

Instance Method Details

#cacheObject

This is the Lightly cache object. You can access or modify cache settings with this object.

Example

client = Client.new
client.cache.life = 3600
client.cache.dir = './cache'
client.cache.disable
client.cache.enable


76
77
78
# File 'lib/apicake/base.rb', line 76

def cache
  @cache ||= Lightly.new
end

#csv_node(data) ⇒ Object

Determins which part of the data is best suited to be displayed as CSV.

  • If the response contains one or more arrays, the first array will be the CSV output

  • Otherwise, if the response was parsed to a ruby object, the response itself will be used as a single-row CSV output.

Override this if you want to have a different decision process.



222
223
224
225
# File 'lib/apicake/base.rb', line 222

def csv_node(data)
  arrays = data.keys.select { |key| data[key].is_a? Array }
  arrays.empty? ? [data] : data[arrays.first]
end

#default_paramsObject

Override this method in order to merge parameters into the HTTParty get request.

Eexample

class Client < APICake::Base
  base_uri: 'http://some.api.com/v3'

  def initialize(user, pass)
    @user, @pass = user, pass
  end

  def default_params
    { basic_auth: { username: user, password: pass }
  end
end


125
126
127
# File 'lib/apicake/base.rb', line 125

def default_params
  {}
end

#default_queryObject

Override this method in order to merge parameters into the query string before each call.

Example

class Client < APICake::Base
  base_uri: 'http://some.api.com/v3'

  def initialize(api_key)
    @api_key = api_key
  end

  def default_query
    { api_key: @api_key }
  end
end

client = Client.new 'secret'
client.some_path param: 'value'
p client.last_url
# => "http://some.api.com/v3/some_path?api_key=secret&param=value"


102
103
104
# File 'lib/apicake/base.rb', line 102

def default_query
  {}
end

#get(path, extra = nil, params = {}) ⇒ Object

Make a request or get it from cache, and return the parsed response.

This is the same as calling #get! and gettings its parsed_response value.

Normally, you should not have the need to use this method, since all unhandled method calls are handled by #method_missing and are delegated here.

Example

client = Client.new
client.get 'path/to/resource', param: value, param: value


143
144
145
# File 'lib/apicake/base.rb', line 143

def get(path, extra = nil, params = {})
  get!(path.clone, extra.clone, params.clone).parsed_response
end

#get!(path, extra = nil, params = {}) ⇒ Object

Make a request or get it from cache, and return the entire Payload object.



149
150
151
152
153
154
155
156
157
158
159
# File 'lib/apicake/base.rb', line 149

def get!(path, extra = nil, params = {})
  path, extra, params = normalize path, extra, params
  key = cache_key path, extra, params

  @last_payload = cache.get key do
    http_get path, params
  end

  @last_url = @last_payload.request.uri.to_s
  @last_payload
end

#get_csv(*args) ⇒ Object

This method uses #get! to download and parse the content. It then makes the best effort to convert the right part of the data to a CSV string.

You can override this method if you wish to provide a different behavior.

Raises:



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/apicake/base.rb', line 190

def get_csv(*args)
  payload = get!(*args)
  raise BadResponse, "#{payload.response.code} #{payload.response.msg}" if payload.response.code != '200'

  response = payload.parsed_response
  raise BadResponse, 'Cannot parse response' unless response.is_a? Hash

  data = csv_node response
  header = data.first.keys

  CSV.generate do |csv|
    csv << header
    data.each { |row| csv << row.values }
  end
end

#respond_to_missing?Boolean

Any undefined method call can be handled by this class.

Returns:

  • (Boolean)


61
62
63
# File 'lib/apicake/base.rb', line 61

def respond_to_missing?(*)
  true
end

#save(filename, path, params = {}) ⇒ Object

Save the response body to a file

Example

client = Client.new
client.save 'out.json', 'some/to/resource', param: value


178
179
180
181
# File 'lib/apicake/base.rb', line 178

def save(filename, path, params = {})
  payload = get! path, nil, params
  File.write filename, payload.response.body
end

#save_csv(file, *args) ⇒ Object

Same as #save, only use the output of #get_csv instead of the response body.



208
209
210
# File 'lib/apicake/base.rb', line 208

def save_csv(file, *args)
  File.write file, get_csv(*args)
end

#url(path, extra = nil, params = {}) ⇒ Object

A shortcut to just get the constructed URL of the request. Note that this call will make the HTTP request (unless it is already cached).

If you have already made the request, you can use #last_url instead.



166
167
168
169
# File 'lib/apicake/base.rb', line 166

def url(path, extra = nil, params = {})
  get! path, extra, params
  last_url
end