Class: ApipieBindings::API
- Inherits:
-
Object
- Object
- ApipieBindings::API
- Defined in:
- lib/apipie_bindings/api.rb
Instance Attribute Summary collapse
-
#apidoc_cache_name ⇒ Object
readonly
Returns the value of attribute apidoc_cache_name.
-
#dry_run ⇒ Object
writeonly
Sets the attribute dry_run.
-
#fake_responses ⇒ Object
readonly
Returns the value of attribute fake_responses.
-
#follow_redirects ⇒ Object
readonly
Returns the value of attribute follow_redirects.
-
#language ⇒ Object
readonly
Returns the value of attribute language.
-
#uri ⇒ Object
readonly
Returns the value of attribute uri.
Instance Method Summary collapse
- #apidoc ⇒ Object
- #apidoc_cache_file ⇒ Object
-
#call(resource_name, action_name, params = {}, headers = {}, options = {}) ⇒ Object
Call an action in the API.
- #call_action(action, params = {}, headers = {}, options = {}) ⇒ Object
- #check_cache ⇒ Object
- #clean_cache ⇒ Object
- #clear_credentials ⇒ Object
- #dry_run? ⇒ Boolean
- #has_resource?(name) ⇒ Boolean
-
#http_call(http_method, path, params = {}, headers = {}, options = {}) ⇒ Object
Low level call to the API.
-
#initialize(config, options = {}) ⇒ API
constructor
Creates new API bindings instance.
- #load_apidoc ⇒ Object
- #log ⇒ Object
- #resource(name) ⇒ Object
-
#resources ⇒ Array<ApipieBindings::Resource>
List available resources.
- #retrieve_apidoc ⇒ Object
- #update_cache(cache_name) ⇒ Object
Constructor Details
#initialize(config, options = {}) ⇒ API
Creates new API bindings instance
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 |
# File 'lib/apipie_bindings/api.rb', line 58 def initialize(config, ={}) if config[:uri].nil? && config[:apidoc_cache_dir].nil? raise ApipieBindings::ConfigurationError.new('Either :uri or :apidoc_cache_dir needs to be set') end @uri = config[:uri] @api_version = config[:api_version] || 1 @language = config[:language] apidoc_cache_base_dir = config[:apidoc_cache_base_dir] || File.join(File.('~/.cache'), 'apipie_bindings') @apidoc_cache_dir = config[:apidoc_cache_dir] || File.join(apidoc_cache_base_dir, @uri.tr(':/', '_'), "v#{@api_version}") @apidoc_cache_name = config[:apidoc_cache_name] || set_default_name @apidoc_authenticated = (config[:apidoc_authenticated].nil? ? true : config[:apidoc_authenticated]) @follow_redirects = config.fetch(:follow_redirects, :default) @dry_run = config[:dry_run] || false @aggressive_cache_checking = config[:aggressive_cache_checking] || false @fake_responses = config[:fake_responses] || {} @logger = config[:logger] unless @logger @logger = Logger.new(STDERR) @logger.level = Logger::ERROR end config = config.dup headers = { :content_type => 'application/json', :accept => "application/json;version=#{@api_version}" } headers.merge!({ "Accept-Language" => language }) if language headers.merge!(config[:headers]) unless config[:headers].nil? headers.merge!(.delete(:headers)) unless [:headers].nil? log.debug "Global headers: #{inspect_data(headers)}" log.debug "Follow redirects: #{@follow_redirects.to_s}" if config[:authenticator] @authenticator = config[:authenticator] else @authenticator = legacy_authenticator(config) end if (config[:timeout] && config[:timeout].to_i < 0) config[:timeout] = (RestClient.version < '1.7.0') ? -1 : nil end # RestClient < 1.7.0 does not support ssl_ca_path use ssl_ca_file instead if [:ssl_ca_path] && !RestClient::Request.method_defined?(:ssl_opts) parsed_uri = URI.parse(@uri) cert_file = File.join([:ssl_ca_path], "#{parsed_uri.host}.pem") if File.exist?(cert_file) [:ssl_ca_file] = cert_file log.warn "ssl_ca_path is not supported by RestClient. ssl_ca_file = #{cert_file} was used instead." end end @resource_config = { :timeout => config[:timeout], :headers => headers, :verify_ssl => true }.merge() @config = config end |
Instance Attribute Details
#apidoc_cache_name ⇒ Object (readonly)
Returns the value of attribute apidoc_cache_name.
9 10 11 |
# File 'lib/apipie_bindings/api.rb', line 9 def apidoc_cache_name @apidoc_cache_name end |
#dry_run=(value) ⇒ Object (writeonly)
Sets the attribute dry_run
10 11 12 |
# File 'lib/apipie_bindings/api.rb', line 10 def dry_run=(value) @dry_run = value end |
#fake_responses ⇒ Object (readonly)
Returns the value of attribute fake_responses.
9 10 11 |
# File 'lib/apipie_bindings/api.rb', line 9 def fake_responses @fake_responses end |
#follow_redirects ⇒ Object (readonly)
Returns the value of attribute follow_redirects.
9 10 11 |
# File 'lib/apipie_bindings/api.rb', line 9 def follow_redirects @follow_redirects end |
#language ⇒ Object (readonly)
Returns the value of attribute language.
9 10 11 |
# File 'lib/apipie_bindings/api.rb', line 9 def language @language end |
#uri ⇒ Object (readonly)
Returns the value of attribute uri.
9 10 11 |
# File 'lib/apipie_bindings/api.rb', line 9 def uri @uri end |
Instance Method Details
#apidoc ⇒ Object
137 138 139 140 |
# File 'lib/apipie_bindings/api.rb', line 137 def apidoc @apidoc ||= load_apidoc || retrieve_apidoc @apidoc end |
#apidoc_cache_file ⇒ Object
122 123 124 |
# File 'lib/apipie_bindings/api.rb', line 122 def apidoc_cache_file File.join(@apidoc_cache_dir, "#{@apidoc_cache_name}#{cache_extension}") end |
#call(resource_name, action_name, params = {}, headers = {}, options = {}) ⇒ Object
Call an action in the API. It finds most fitting route based on given parameters with other attributes necessary to do an API call. If in dry_run mode #initialize it finds fake response data in examples or user provided data. At the end when the response format is JSON it is parsed and returned as ruby objects. If server supports checksum sending the internal cache with API description is checked and updated if needed
178 179 180 181 182 183 184 185 186 |
# File 'lib/apipie_bindings/api.rb', line 178 def call(resource_name, action_name, params={}, headers={}, ={}) check_cache if @aggressive_cache_checking resource = resource(resource_name) action = resource.action(action_name) action.validate!(params) unless [:skip_validation] [:fake_response] = find_match(fake_responses, resource_name, action_name, params) || action.examples.first if dry_run? call_action(action, params, headers, ) end |
#call_action(action, params = {}, headers = {}, options = {}) ⇒ Object
188 189 190 191 192 193 194 195 |
# File 'lib/apipie_bindings/api.rb', line 188 def call_action(action, params={}, headers={}, ={}) route = action.find_route(params) return http_call( route.method, route.path(params), params.reject { |par, _| route.params_in_path.include? par.to_s }, headers, ) end |
#check_cache ⇒ Object
273 274 275 276 277 278 279 280 |
# File 'lib/apipie_bindings/api.rb', line 273 def check_cache begin response = http_call('get', "/apidoc/apipie_checksum", {}, { :accept => "application/json" }) response['checksum'] rescue nil end end |
#clean_cache ⇒ Object
268 269 270 271 |
# File 'lib/apipie_bindings/api.rb', line 268 def clean_cache @apidoc = nil Dir["#{@apidoc_cache_dir}/*#{cache_extension}"].each { |f| File.delete(f) } end |
#clear_credentials ⇒ Object
133 134 135 |
# File 'lib/apipie_bindings/api.rb', line 133 def clear_credentials @authenticator.clear if @authenticator && @authenticator.respond_to?(:clear) end |
#dry_run? ⇒ Boolean
142 143 144 |
# File 'lib/apipie_bindings/api.rb', line 142 def dry_run? @dry_run ? true : false end |
#has_resource?(name) ⇒ Boolean
146 147 148 |
# File 'lib/apipie_bindings/api.rb', line 146 def has_resource?(name) apidoc[:docs][:resources].has_key? name end |
#http_call(http_method, path, params = {}, headers = {}, options = {}) ⇒ Object
Low level call to the API. Suitable for calling actions not covered by apipie documentation. For all other cases use #call
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 |
# File 'lib/apipie_bindings/api.rb', line 209 def http_call(http_method, path, params={}, headers={}, ={}) headers ||= { } args = [http_method] if %w[post put].include?(http_method.to_s) #If using multi-part forms, the paramaters should not be json if ((headers.include?(:content_type)) and (headers[:content_type] == "multipart/form-data")) args << params else args << params.to_json end else headers[:params] = params if params end log.info "Server: #{@uri}" log.info "#{http_method.to_s.upcase} #{path}" log.debug "Params: #{inspect_data(params)}" log.debug "Headers: #{inspect_data(headers)}" args << headers if headers if dry_run? empty_response = ApipieBindings::Example.new('', '', '', 200, '') ex = [:fake_response ] || empty_response response = create_fake_response(ex.status, ex.response, http_method, URI.join(@uri || 'http://example.com', path).to_s, args) else apidoc_without_auth = (path =~ /\/apidoc\//) && !@apidoc_authenticated authenticate = [:with_authentication].nil? ? !apidoc_without_auth : [:with_authentication] begin client = authenticate ? authenticated_client : unauthenticated_client response = call_client(client, path, args) update_cache(response.headers[:apipie_checksum]) rescue => e log.error e. log.debug inspect_data(e) if e.respond_to?(:response) && e.response.respond_to?(:headers) update_cache(e.response.headers[:apipie_checksum]) end override_e = @authenticator.error(e) if authenticate && @authenticator raise override_e.is_a?(StandardError) ? override_e : e end end result = [:response] == :raw ? response : process_data(response) log.debug "Response: %s" % ([:reduce_response_log] ? "Received OK" : inspect_data(result)) log.debug "Response headers: #{inspect_data(response.headers)}" if response.respond_to?(:headers) result end |
#load_apidoc ⇒ Object
126 127 128 129 130 131 |
# File 'lib/apipie_bindings/api.rb', line 126 def load_apidoc check_cache if @aggressive_cache_checking if File.exist?(apidoc_cache_file) JSON.parse(File.read(apidoc_cache_file), :symbolize_names => true) end end |
#log ⇒ Object
306 307 308 |
# File 'lib/apipie_bindings/api.rb', line 306 def log @logger end |
#resource(name) ⇒ Object
150 151 152 |
# File 'lib/apipie_bindings/api.rb', line 150 def resource(name) ApipieBindings::Resource.new(name, self) end |
#resources ⇒ Array<ApipieBindings::Resource>
List available resources
156 157 158 |
# File 'lib/apipie_bindings/api.rb', line 156 def resources apidoc[:docs][:resources].keys.map { |res| resource(res) } end |
#retrieve_apidoc ⇒ Object
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 |
# File 'lib/apipie_bindings/api.rb', line 282 def retrieve_apidoc FileUtils.mkdir_p(@apidoc_cache_dir) unless File.exist?(@apidoc_cache_dir) if language response = retrieve_apidoc_call("/apidoc/v#{@api_version}.#{language}.json", :safe => true) language_family = language.split('_').first if !response && language_family != language response = retrieve_apidoc_call("/apidoc/v#{@api_version}.#{language_family}.json", :safe => true) end end unless response begin response = retrieve_apidoc_call("/apidoc/v#{@api_version}.json") rescue Exception => e raise ApipieBindings::DocLoadingError.new( "Could not load data from #{@uri}: #{e.}\n"\ " - is your server down?\n"\ " - was rake apipie:cache run when using apipie cache? (typical production settings)", e) end end File.open(apidoc_cache_file, "w") { |f| f.write(response.body) } log.debug "New apidoc loaded from the server" load_apidoc end |
#update_cache(cache_name) ⇒ Object
260 261 262 263 264 265 266 |
# File 'lib/apipie_bindings/api.rb', line 260 def update_cache(cache_name) if !cache_name.nil? && (cache_name != @apidoc_cache_name) clean_cache log.debug "Cache expired. (#{@apidoc_cache_name} -> #{cache_name})" @apidoc_cache_name = cache_name end end |