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
-
#call_api(http_method, path, opts = {}, required_scopes = "", is_retry = false) ⇒ 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
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/avalara_sdk/api_client.rb', line 49 def initialize(config) if (config.nil?) fail ArgumentError,'configuration is nil' end @base_path=config.base_url() @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
45 46 47 |
# File 'lib/avalara_sdk/api_client.rb', line 45 def access_token_map @access_token_map end |
#config ⇒ Object
The Configuration object holding settings to be used in the API client.
31 32 33 |
# File 'lib/avalara_sdk/api_client.rb', line 31 def config @config end |
#default_headers ⇒ Hash
Defines the headers to be used in HTTP requests of all API calls by default.
39 40 41 |
# File 'lib/avalara_sdk/api_client.rb', line 39 def default_headers @default_headers end |
#sdk_version ⇒ Object
The sdk version to be set in header
34 35 36 |
# File 'lib/avalara_sdk/api_client.rb', line 34 def sdk_version @sdk_version end |
#token_url ⇒ Object
The token url that will be used for the OAuth2 flows
42 43 44 |
# File 'lib/avalara_sdk/api_client.rb', line 42 def token_url @token_url end |
Class Method Details
Instance Method Details
#apply_auth_to_request!(header_params, auth_names, required_scopes) ⇒ Object
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 |
# File 'lib/avalara_sdk/api_client.rb', line 314 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.
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 |
# File 'lib/avalara_sdk/api_client.rb', line 296 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
356 357 358 359 360 361 362 363 364 365 366 367 368 |
# File 'lib/avalara_sdk/api_client.rb', line 356 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
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 |
# File 'lib/avalara_sdk/api_client.rb', line 142 def build_request(http_method, path, request, opts = {}) url = build_request_url(path, opts) http_method = http_method.to_sym.downcase header_params = @default_headers.merge(opts[:header_params] || {}) header_params['X-Avalara-Client']="#{@config.app_name};#{@config.app_version};RubySdk;#{@sdk_version};#{@config.machine_name}" query_params = opts[:query_params] || {} form_params = opts[:form_params] || {} req_opts = { :params_encoding => @config.params_encoding, :timeout => @config.timeout, :verbose => @config.debugging } if [:post, :patch, :put, :delete].include?(http_method) 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~\n" end end request.headers = header_params request.body = req_body request. = OpenStruct.new(req_opts) request.url 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
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 |
# File 'lib/avalara_sdk/api_client.rb', line 178 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
234 235 236 237 238 |
# File 'lib/avalara_sdk/api_client.rb', line 234 def build_request_url(path, opts = {}) # Add leading and trailing slashes to path path = "/#{path}".gsub(/\/+/, '/') @config.base_url() + path end |
#call_api(http_method, path, opts = {}, required_scopes = "", is_retry = false) ⇒ Array<(Object, Integer, Hash)>
Call an API with given options.
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 123 124 125 126 127 128 129 130 131 |
# File 'lib/avalara_sdk/api_client.rb', line 79 def call_api(http_method, path, opts = {}, required_scopes = "", is_retry = false) = { :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 } connection = Faraday.new(:url => config.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| 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) 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
370 371 372 |
# File 'lib/avalara_sdk/api_client.rb', line 370 def create_basic_auth_header(username, password) "Basic #{Base64.encode64("#{username}:#{password}")}" end |
#download_file(request) ⇒ Object
204 205 206 207 208 209 210 211 |
# File 'lib/avalara_sdk/api_client.rb', line 204 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
331 332 333 334 335 336 337 338 339 340 |
# File 'lib/avalara_sdk/api_client.rb', line 331 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
*/*
221 222 223 |
# File 'lib/avalara_sdk/api_client.rb', line 221 def json_mime?(mime) (mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil? end |
#object_to_hash(obj) ⇒ String
Convert object(non-array) to hash.
286 287 288 289 290 291 292 |
# File 'lib/avalara_sdk/api_client.rb', line 286 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.
272 273 274 275 276 277 278 279 280 281 |
# File 'lib/avalara_sdk/api_client.rb', line 272 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
230 231 232 |
# File 'lib/avalara_sdk/api_client.rb', line 230 def sanitize_filename(filename) filename.gsub(/.*[\/\\]/, '') end |
#select_header_accept(accepts) ⇒ String
Return Accept header based on an array of accepts provided.
251 252 253 254 255 256 |
# File 'lib/avalara_sdk/api_client.rb', line 251 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.
261 262 263 264 265 266 267 |
# File 'lib/avalara_sdk/api_client.rb', line 261 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
71 72 73 |
# File 'lib/avalara_sdk/api_client.rb', line 71 def set_sdk_version(sdk_version="") @sdk_version=sdk_version end |
#standardize_scopes(required_scopes) ⇒ Object
374 375 376 377 378 |
# File 'lib/avalara_sdk/api_client.rb', line 374 def standardize_scopes(required_scopes) scopes = required_scopes.split(" ") scopes.sort scopes.join(" ") end |
#update_oauth_access_token(required_scopes, access_token) ⇒ Object
342 343 344 345 346 347 348 349 350 351 352 353 354 |
# File 'lib/avalara_sdk/api_client.rb', line 342 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
243 244 245 246 |
# File 'lib/avalara_sdk/api_client.rb', line 243 def user_agent=(user_agent) @user_agent = user_agent @default_headers['User-Agent'] = @user_agent end |