Class: AvalaraSdk::ApiClient
- Inherits:
-
Object
- Object
- AvalaraSdk::ApiClient
- Defined in:
- lib/avalara_sdk/api_client.rb
Constant Summary collapse
- PRODUCTION_OPENID_CONFIG_URL =
'https://identity.avalara.com/.well-known/openid-configuration'- SANDBOX_OPENID_CONFIG_URL =
'https://ai-sbx.avlr.sh/.well-known/openid-configuration'- QA_OPENID_CONFIG_URL =
'https://ai-awsfqa.avlr.sh/.well-known/openid-configuration'
Instance Attribute Summary collapse
-
#access_token_map ⇒ Object
The in-memory cache for access tokens.
-
#config ⇒ Object
The Configuration object holding settings to be used in the API client.
-
#default_headers ⇒ Hash
Defines the headers to be used in HTTP requests of all API calls by default.
-
#sdk_version ⇒ Object
The sdk version to be set in header.
-
#token_url ⇒ Object
The token url that will be used for the OAuth2 flows.
Class Method Summary collapse
Instance Method Summary collapse
- #apply_auth_to_request!(header_params, auth_names, required_scopes) ⇒ Object
-
#build_collection_param(param, collection_format) ⇒ Object
Build parameter value according to the given collection format.
- #build_oauth_request(required_scopes) ⇒ Object
-
#build_request(http_method, path, request, opts = {}) ⇒ Faraday::Request
Builds the HTTP request.
-
#build_request_body(header_params, form_params, body) ⇒ String
Builds the HTTP request body.
-
#build_request_url(path, opts = {}) ⇒ Object
Builds the HTTP request URL fragment now returns a path WITHOUT a leading slash.
-
#call_api(http_method, path, opts = {}, required_scopes = "", is_retry = false, microservice = AvalaraSdk::AvalaraMicroservice::NONE) ⇒ Array<(Object, Integer, Hash)>
Call an API with given options.
- #create_basic_auth_header(username, password) ⇒ Object
- #download_file(request) ⇒ Object
- #get_oauth_access_token(required_scopes) ⇒ Object
-
#initialize(config) ⇒ ApiClient
constructor
Initializes the ApiClient.
-
#json_mime?(mime) ⇒ Boolean
Check if the given MIME is a JSON MIME.
-
#object_to_hash(obj) ⇒ String
Convert object(non-array) to hash.
-
#object_to_http_body(model) ⇒ String
Convert object (array, hash, object, etc) to JSON string.
-
#sanitize_filename(filename) ⇒ String
Sanitize filename by removing path.
-
#select_header_accept(accepts) ⇒ String
Return Accept header based on an array of accepts provided.
-
#select_header_content_type(content_types) ⇒ String
Return Content-Type header based on an array of content types provided.
- #set_sdk_version(sdk_version = "") ⇒ Object
- #standardize_scopes(required_scopes) ⇒ Object
- #update_oauth_access_token(required_scopes, access_token) ⇒ Object
-
#user_agent=(user_agent) ⇒ Object
Sets user agent in HTTP header.
Constructor Details
#initialize(config) ⇒ ApiClient
Initializes the ApiClient
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/avalara_sdk/api_client.rb', line 38 def initialize(config) if (config.nil?) fail ArgumentError,'configuration is nil' end @sdk_version="" @config = config @default_headers = { 'Content-Type' => 'application/json', 'User-Agent' => @user_agent } @access_token_map = Hash.new @token_url="" end |
Instance Attribute Details
#access_token_map ⇒ Object
The in-memory cache for access tokens
34 35 36 |
# File 'lib/avalara_sdk/api_client.rb', line 34 def access_token_map @access_token_map end |
#config ⇒ Object
The Configuration object holding settings to be used in the API client.
20 21 22 |
# File 'lib/avalara_sdk/api_client.rb', line 20 def config @config end |
#default_headers ⇒ Hash
Defines the headers to be used in HTTP requests of all API calls by default.
28 29 30 |
# File 'lib/avalara_sdk/api_client.rb', line 28 def default_headers @default_headers end |
#sdk_version ⇒ Object
The sdk version to be set in header
23 24 25 |
# File 'lib/avalara_sdk/api_client.rb', line 23 def sdk_version @sdk_version end |
#token_url ⇒ Object
The token url that will be used for the OAuth2 flows
31 32 33 |
# File 'lib/avalara_sdk/api_client.rb', line 31 def token_url @token_url end |
Class Method Details
Instance Method Details
#apply_auth_to_request!(header_params, auth_names, required_scopes) ⇒ Object
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 |
# File 'lib/avalara_sdk/api_client.rb', line 330 def apply_auth_to_request!(header_params, auth_names, required_scopes) if !@config.bearer_token.nil? && @config.bearer_token.length != 0 header_params['Authorization'] = "Bearer #{@config.bearer_token}" elsif auth_names.include?("OAuth") && !@config.client_id.nil? && !@config.client_secret.nil? && @config.client_id.length != 0 && @config.client_secret.length != 0 scopes = standardize_scopes required_scopes access_token = get_oauth_access_token scopes if access_token.nil? update_oauth_access_token required_scopes, nil access_token = get_oauth_access_token required_scopes end header_params['Authorization'] = "Bearer #{access_token}" elsif !@config.username.nil? && !@config.password.nil? && @config.username.length != 0 && @config.password.length != 0 header_params['Authorization'] = create_basic_auth_header @config.username, @config.password end end |
#build_collection_param(param, collection_format) ⇒ Object
Build parameter value according to the given collection format.
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 |
# File 'lib/avalara_sdk/api_client.rb', line 312 def build_collection_param(param, collection_format) case collection_format when :csv param.join(',') when :ssv param.join(' ') when :tsv param.join("\t") when :pipes param.join('|') when :multi # return the array directly as typhoeus will handle it as expected param else fail "unknown collection format: #{collection_format.inspect}" end end |
#build_oauth_request(required_scopes) ⇒ Object
372 373 374 375 376 377 378 379 380 381 382 383 384 |
# File 'lib/avalara_sdk/api_client.rb', line 372 def build_oauth_request(required_scopes) @config.populate_token_url = create_basic_auth_header @config.client_id, @config.client_secret data = { "grant_type"=>"client_credentials", "scope"=>"#{required_scopes}" } response = Faraday.post(@config.token_url) do |req| req.headers['Content-Type'] = 'application/x-www-form-urlencoded' req.headers['Authorization'] = req.headers['Accept'] = 'application/json' req.body = URI.encode_www_form(data) end JSON.parse(response.body) end |
#build_request(http_method, path, request, opts = {}) ⇒ Faraday::Request
Builds the HTTP request
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 |
# File 'lib/avalara_sdk/api_client.rb', line 133 def build_request(http_method, path, request, opts = {}) # Compute a relative URL (no leading slash) so Faraday merges correctly relative_url = build_request_url(path).sub(%r{^/}, '') header_params = @default_headers.merge(opts[:header_params] || {}) sdk_client_header = "#{@config.app_name};#{@config.app_version};RubySdk;#{@sdk_version};#{@config.machine_name}" # Always set X-Avalara-SDK-Client to SDK info header_params['X-Avalara-SDK-Client'] = sdk_client_header # If X-Avalara-Client is null/empty, set it to SDK info as well if header_params['X-Avalara-Client'].nil? || header_params['X-Avalara-Client'].empty? header_params['X-Avalara-Client'] = sdk_client_header end query_params = opts[:query_params] || {} form_params = opts[:form_params] || {} # Build body if needed http_method_sym = http_method.to_sym.downcase if [:post, :patch, :put, :delete].include?(http_method_sym) req_body = build_request_body(header_params, form_params, opts[:body]) if @config.debugging @config.logger.debug "HTTP request body param ~BEGIN~\n\#{req_body}\n~END~" end end # Apply headers, body, and options request.headers = header_params request.body = req_body request. = OpenStruct.new( params_encoding: @config.params_encoding, timeout: @config.timeout, verbose: @config.debugging ) # Use a relative path so URL prefix (/avalara1099/) is preserved request.url relative_url request.params = query_params download_file(request) if opts[:return_type] == 'File' request end |
#build_request_body(header_params, form_params, body) ⇒ String
Builds the HTTP request body
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 |
# File 'lib/avalara_sdk/api_client.rb', line 193 def build_request_body(header_params, form_params, body) # http form if header_params['Content-Type'] == 'application/x-www-form-urlencoded' data = URI.encode_www_form(form_params) elsif header_params['Content-Type'] == 'multipart/form-data' data = {} form_params.each do |key, value| case value when ::File, ::Tempfile # TODO hardcode to application/octet-stream, need better way to detect content type data[key] = Faraday::UploadIO.new(value.path, 'application/octet-stream', value.path) when ::Array, nil # let Faraday handle Array and nil parameters data[key] = value else data[key] = value.to_s end end elsif body data = body.is_a?(String) ? body : body.to_json else data = nil end data end |
#build_request_url(path, opts = {}) ⇒ Object
Builds the HTTP request URL fragment now returns a path WITHOUT a leading slash
180 181 182 183 184 185 |
# File 'lib/avalara_sdk/api_client.rb', line 180 def build_request_url(path) # Normalize slashes clean = "/\#{path}".gsub(/\/+/, '/') # Drop leading slash for Faraday-relative URLs clean.sub(%r{^/}, '') end |
#call_api(http_method, path, opts = {}, required_scopes = "", is_retry = false, microservice = AvalaraSdk::AvalaraMicroservice::NONE) ⇒ Array<(Object, Integer, Hash)>
Call an API with given options.
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 120 121 122 |
# File 'lib/avalara_sdk/api_client.rb', line 67 def call_api(http_method, path, opts = {}, required_scopes = "", is_retry = false, microservice = AvalaraSdk::AvalaraMicroservice::NONE) = { :ca_file => @config.ssl_ca_file, :verify => @config.ssl_verify, :verify_mode => @config.ssl_verify_mode, :client_cert => @config.ssl_client_cert, :client_key => @config.ssl_client_key } base_url = @config.get_base_path(microservice) connection = Faraday.new(:url => base_url, :ssl => ) do |conn| @config.configure_middleware(conn) if opts[:header_params]["Content-Type"] == "multipart/form-data" conn.request :multipart conn.request :url_encoded end conn.adapter(Faraday.default_adapter) end begin response = connection.public_send(http_method.to_sym.downcase) do |req| full_url = connection.build_url(path, opts[:query_params]) build_request(http_method, path, req, opts) end if @config.debugging @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" end unless response.success? if (response.status == 401 || response.status == 403) && !is_retry && !@config.client_id.nil? && !@config.client_secret.nil? && @config.client_id.length != 0 && @config.client_secret.length != 0 = opts[:header_params]["Authorization"] values = .split(" ") if !values.nil? && values.length == 2 update_oauth_access_token(required_scopes, values[1]) call_api(http_method, path, opts, required_scopes, true, microservice) end elsif response.status == 0 # Errors from libcurl will be made visible here fail ApiError.new(:code => 0, :message => response.) else fail ApiError.new(:code => response.status, :response_headers => response.headers, :response_body => response.body), response.reason_phrase end end rescue Faraday::TimeoutError fail ApiError.new('Connection timed out') end return AvalaraSdk::ResponseHash.new(response.body, response.headers, response.status) end |
#create_basic_auth_header(username, password) ⇒ Object
386 387 388 |
# File 'lib/avalara_sdk/api_client.rb', line 386 def create_basic_auth_header(username, password) "Basic #{Base64.encode64("#{username}:#{password}")}" end |
#download_file(request) ⇒ Object
219 220 221 222 223 224 225 226 |
# File 'lib/avalara_sdk/api_client.rb', line 219 def download_file(request) @stream = [] # handle streaming Responses request..on_data = Proc.new do |chunk, overall_received_bytes| @stream << chunk end end |
#get_oauth_access_token(required_scopes) ⇒ Object
347 348 349 350 351 352 353 354 355 356 |
# File 'lib/avalara_sdk/api_client.rb', line 347 def get_oauth_access_token(required_scopes) = @access_token_map[required_scopes] if !.nil? expiration_time = Time.now + 300 if expiration_time < .expiry return .access_token end end return nil end |
#json_mime?(mime) ⇒ Boolean
Check if the given MIME is a JSON MIME. JSON MIME examples:
application/json
application/json; charset=UTF8
APPLICATION/JSON
*/*
236 237 238 |
# File 'lib/avalara_sdk/api_client.rb', line 236 def json_mime?(mime) (mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil? end |
#object_to_hash(obj) ⇒ String
Convert object(non-array) to hash.
302 303 304 305 306 307 308 |
# File 'lib/avalara_sdk/api_client.rb', line 302 def object_to_hash(obj) if obj.respond_to?(:to_hash) obj.to_hash else obj end end |
#object_to_http_body(model) ⇒ String
Convert object (array, hash, object, etc) to JSON string.
288 289 290 291 292 293 294 295 296 297 |
# File 'lib/avalara_sdk/api_client.rb', line 288 def object_to_http_body(model) return model if model.nil? || model.is_a?(String) local_body = nil if model.is_a?(Array) local_body = model.map { |m| object_to_hash(m) } else local_body = object_to_hash(model) end local_body.to_json end |
#sanitize_filename(filename) ⇒ String
Sanitize filename by removing path. e.g. ../../sun.gif becomes sun.gif
245 246 247 |
# File 'lib/avalara_sdk/api_client.rb', line 245 def sanitize_filename(filename) filename.gsub(/.*[\/\\]/, '') end |
#select_header_accept(accepts) ⇒ String
Return Accept header based on an array of accepts provided.
267 268 269 270 271 272 |
# File 'lib/avalara_sdk/api_client.rb', line 267 def select_header_accept(accepts) return nil if accepts.nil? || accepts.empty? # use JSON when present, otherwise use all of the provided json_accept = accepts.find { |s| json_mime?(s) } json_accept || accepts.join(',') end |
#select_header_content_type(content_types) ⇒ String
Return Content-Type header based on an array of content types provided.
277 278 279 280 281 282 283 |
# File 'lib/avalara_sdk/api_client.rb', line 277 def select_header_content_type(content_types) # return nil by default return if content_types.nil? || content_types.empty? # use JSON when present, otherwise use the first one json_content_type = content_types.find { |s| json_mime?(s) } json_content_type || content_types.first end |
#set_sdk_version(sdk_version = "") ⇒ Object
59 60 61 |
# File 'lib/avalara_sdk/api_client.rb', line 59 def set_sdk_version(sdk_version="") @sdk_version=sdk_version end |
#standardize_scopes(required_scopes) ⇒ Object
390 391 392 393 394 |
# File 'lib/avalara_sdk/api_client.rb', line 390 def standardize_scopes(required_scopes) scopes = required_scopes.split(" ") scopes.sort scopes.join(" ") end |
#update_oauth_access_token(required_scopes, access_token) ⇒ Object
358 359 360 361 362 363 364 365 366 367 368 369 370 |
# File 'lib/avalara_sdk/api_client.rb', line 358 def update_oauth_access_token(required_scopes, access_token) current_access_token = get_oauth_access_token required_scopes if current_access_token.nil? || current_access_token == access_token begin data = build_oauth_request required_scopes = Time.now + data['expires_in'].to_i @access_token_map[required_scopes] = AvalaraSdk::TokenMetadata.new(data['access_token'], ) rescue Exception => e puts "OAuth2 Token retrieval failed. Error: #{e.}" raise "OAuth2 Token retrieval failed. Error: #{e.}" end end end |
#user_agent=(user_agent) ⇒ Object
Sets user agent in HTTP header
259 260 261 262 |
# File 'lib/avalara_sdk/api_client.rb', line 259 def user_agent=(user_agent) @user_agent = user_agent @default_headers['User-Agent'] = @user_agent end |