Class: Google::APIClient
- Inherits:
-
Object
- Object
- Google::APIClient
- Includes:
- Logging
- Defined in:
- lib/google/api_client.rb,
lib/google/api_client/gzip.rb,
lib/google/api_client/batch.rb,
lib/google/api_client/media.rb,
lib/google/api_client/errors.rb,
lib/google/api_client/result.rb,
lib/google/api_client/charset.rb,
lib/google/api_client/logging.rb,
lib/google/api_client/railtie.rb,
lib/google/api_client/request.rb,
lib/google/api_client/service.rb,
lib/google/api_client/version.rb,
lib/google/api_client/reference.rb,
lib/google/api_client/auth/pkcs12.rb,
lib/google/api_client/environment.rb,
lib/google/api_client/auth/storage.rb,
lib/google/api_client/discovery/api.rb,
lib/google/api_client/service/batch.rb,
lib/google/api_client/auth/key_utils.rb,
lib/google/api_client/client_secrets.rb,
lib/google/api_client/service/result.rb,
lib/google/api_client/discovery/media.rb,
lib/google/api_client/service/request.rb,
lib/google/api_client/discovery/method.rb,
lib/google/api_client/discovery/schema.rb,
lib/google/api_client/service/resource.rb,
lib/google/api_client/auth/file_storage.rb,
lib/google/api_client/auth/jwt_asserter.rb,
lib/google/api_client/auth/installed_app.rb,
lib/google/api_client/discovery/resource.rb,
lib/google/api_client/service/stub_generator.rb,
lib/google/api_client/auth/storages/file_store.rb,
lib/google/api_client/auth/storages/redis_store.rb,
lib/google/api_client/service/simple_file_store.rb,
lib/google/api_client/auth/compute_service_account.rb
Overview
This class manages APIs communication.
Defined Under Namespace
Modules: ENV, KeyUtils, Logging, PKCS12, Schema, VERSION Classes: API, AuthorizationError, BatchError, BatchRequest, BatchedCallResponse, Charset, ClientError, ClientSecrets, ComputeServiceAccount, FileStorage, FileStore, Gzip, InstalledAppFlow, InvalidIDTokenError, JWTAsserter, MediaUpload, Method, Railtie, RangedIO, RedirectError, RedisStore, Reference, Request, Resource, Result, ResumableUpload, ServerError, Service, Storage, TransmissionError, UploadIO, ValidationError
Class Attribute Summary collapse
-
.logger ⇒ Logger
Logger for the API client.
Instance Attribute Summary collapse
-
#authorization ⇒ #generate_authenticated_request
Returns the authorization mechanism used by the client.
-
#auto_refresh_token ⇒ Boolean
The setting that controls whether or not the api client attempts to refresh authorization when a 401 is hit in #execute.
-
#connection ⇒ Faraday::Connection
Default Faraday/HTTP connection.
-
#discovery_path ⇒ String
The base path used by the client for discovery.
-
#expired_auth_retry ⇒ Boolean
Whether or not an expired auth token should be re-acquired (and the operation retried) regardless of retries setting.
-
#host ⇒ String
The API hostname used by the client.
-
#key ⇒ String
The application's API key issued by the API console.
-
#port ⇒ String
The port number used by the client.
-
#retries ⇒ FixNum
Number of times to retry on recoverable errors.
-
#user_agent ⇒ String
The user agent used by the client.
-
#user_ip ⇒ String
The IP address of the user this request is being performed on behalf of.
Instance Method Summary collapse
-
#directory_document ⇒ Hash
Returns the parsed directory document.
-
#directory_uri ⇒ Addressable::URI
Returns the URI for the directory document.
-
#discovered_api(api, version = nil) ⇒ Google::APIClient::API
Returns the service object for a given service name and service version.
-
#discovered_apis ⇒ Array
Returns all APIs published in the directory document.
-
#discovered_method(rpc_name, api, version = nil) ⇒ Google::APIClient::Method
Returns the method object for a given RPC name and service version.
-
#discovery_document(api, version = nil) ⇒ Hash
Returns the parsed discovery document.
-
#discovery_uri(api, version = nil) ⇒ Addressable::URI
Returns the URI for the discovery document.
-
#execute(*params) ⇒ Object
Same as Google::APIClient#execute!, but does not raise an exception for normal API errros.
-
#execute!(*params) ⇒ Google::APIClient::Result
Executes a request, wrapping it in a Result object.
-
#generate_request(options = {}) ⇒ Google::APIClient::Reference
Generates a request.
-
#initialize(options = {}) ⇒ APIClient
constructor
Creates a new Google API client.
-
#preferred_version(api) ⇒ Google::APIClient::API
Returns the service object with the highest version number.
-
#register_discovery_document(api, version, discovery_document) ⇒ Google::APIClient::API
Manually registers a pre-loaded discovery document for a specific version of an API.
-
#register_discovery_uri(api, version, uri) ⇒ Google::APIClient::API
Manually registers a URI as a discovery document for a specific version of an API.
-
#verify_id_token! ⇒ Object
deprecated
Deprecated.
Use the google-id-token gem for verifying JWTs
Methods included from Logging
Constructor Details
#initialize(options = {}) ⇒ APIClient
Creates a new Google API client.
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 132 133 134 135 136 137 138 139 140 141 |
# File 'lib/google/api_client.rb', line 84 def initialize(={}) logger.debug { "#{self.class} - Initializing client with options #{}" } # Normalize key to String to allow indifferent access. = .inject({}) do |accu, (key, value)| accu[key.to_sym] = value accu end # Almost all API usage will have a host of 'www.googleapis.com'. self.host = [:host] || 'www.googleapis.com' self.port = [:port] || 443 self.discovery_path = [:discovery_path] || '/discovery/v1' # Most developers will want to leave this value alone and use the # application_name option. if [:application_name] app_name = [:application_name] app_version = [:application_version] application_string = "#{app_name}/#{app_version || '0.0.0'}" else logger.warn { "#{self.class} - Please provide :application_name and :application_version when initializing the client" } end proxy = [:proxy] || Object::ENV["http_proxy"] self.user_agent = [:user_agent] || ( "#{application_string} " + "google-api-ruby-client/#{Google::APIClient::VERSION::STRING} #{ENV::OS_VERSION} (gzip)" ).strip # The writer method understands a few Symbols and will generate useful # default authentication mechanisms. self. = .key?(:authorization) ? [:authorization] : :oauth_2 self.auto_refresh_token = .fetch(:auto_refresh_token) { true } self.key = [:key] self.user_ip = [:user_ip] self.retries = .fetch(:retries) { 0 } self.expired_auth_retry = .fetch(:expired_auth_retry) { true } @discovery_uris = {} @discovery_documents = {} @discovered_apis = {} ca_file = [:ca_file] || File.('../../cacerts.pem', __FILE__) self.connection = Faraday.new do |faraday| faraday.response :charset if [:force_encoding] faraday.response :gzip faraday..params_encoder = Faraday::FlatParamsEncoder faraday.ssl.ca_file = ca_file faraday.ssl.verify = true faraday.proxy proxy faraday.adapter Faraday.default_adapter if [:faraday_option].is_a?(Hash) [:faraday_option].each_pair do |option, value| faraday..send("#{option}=", value) end end end return self end |
Class Attribute Details
.logger ⇒ Logger
Logger for the API client
11 12 13 |
# File 'lib/google/api_client/logging.rb', line 11 def logger @logger end |
Instance Attribute Details
#authorization ⇒ #generate_authenticated_request
Returns the authorization mechanism used by the client.
147 148 149 |
# File 'lib/google/api_client.rb', line 147 def @authorization end |
#auto_refresh_token ⇒ Boolean
The setting that controls whether or not the api client attempts to refresh authorization when a 401 is hit in #execute.
210 211 212 |
# File 'lib/google/api_client.rb', line 210 def auto_refresh_token @auto_refresh_token end |
#connection ⇒ Faraday::Connection
Default Faraday/HTTP connection.
203 204 205 |
# File 'lib/google/api_client.rb', line 203 def connection @connection end |
#discovery_path ⇒ String
The base path used by the client for discovery.
250 251 252 |
# File 'lib/google/api_client.rb', line 250 def discovery_path @discovery_path end |
#expired_auth_retry ⇒ Boolean
Whether or not an expired auth token should be re-acquired (and the operation retried) regardless of retries setting
264 265 266 |
# File 'lib/google/api_client.rb', line 264 def expired_auth_retry @expired_auth_retry end |
#host ⇒ String
The API hostname used by the client.
236 237 238 |
# File 'lib/google/api_client.rb', line 236 def host @host end |
#key ⇒ String
The application's API key issued by the API console.
216 217 218 |
# File 'lib/google/api_client.rb', line 216 def key @key end |
#port ⇒ String
The port number used by the client.
243 244 245 |
# File 'lib/google/api_client.rb', line 243 def port @port end |
#retries ⇒ FixNum
Number of times to retry on recoverable errors
257 258 259 |
# File 'lib/google/api_client.rb', line 257 def retries @retries end |
#user_agent ⇒ String
The user agent used by the client.
229 230 231 |
# File 'lib/google/api_client.rb', line 229 def user_agent @user_agent end |
#user_ip ⇒ String
The IP address of the user this request is being performed on behalf of.
222 223 224 |
# File 'lib/google/api_client.rb', line 222 def user_ip @user_ip end |
Instance Method Details
#directory_document ⇒ Hash
Returns the parsed directory document.
337 338 339 340 341 342 343 344 345 346 |
# File 'lib/google/api_client.rb', line 337 def directory_document return @directory_document ||= (begin response = self.execute!( :http_method => :get, :uri => self.directory_uri, :authenticated => false ) response.data end) end |
#directory_uri ⇒ Addressable::URI
Returns the URI for the directory document.
270 271 272 |
# File 'lib/google/api_client.rb', line 270 def directory_uri return resolve_uri(self.discovery_path + '/apis') end |
#discovered_api(api, version = nil) ⇒ Google::APIClient::API
Returns the service object for a given service name and service version.
394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 |
# File 'lib/google/api_client.rb', line 394 def discovered_api(api, version=nil) if !api.kind_of?(String) && !api.kind_of?(Symbol) raise TypeError, "Expected String or Symbol, got #{api.class}." end api = api.to_s version = version || 'v1' return @discovered_apis["#{api}:#{version}"] ||= begin document_base = self.discovery_uri(api, version) discovery_document = self.discovery_document(api, version) if document_base && discovery_document Google::APIClient::API.new( document_base, discovery_document ) else nil end end end |
#discovered_apis ⇒ Array
Returns all APIs published in the directory document.
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 |
# File 'lib/google/api_client.rb', line 371 def discovered_apis @directory_apis ||= (begin document_base = self.directory_uri if self.directory_document && self.directory_document['items'] self.directory_document['items'].map do |discovery_document| Google::APIClient::API.new( document_base, discovery_document ) end else [] end end) end |
#discovered_method(rpc_name, api, version = nil) ⇒ Google::APIClient::Method
Returns the method object for a given RPC name and service version.
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 |
# File 'lib/google/api_client.rb', line 423 def discovered_method(rpc_name, api, version=nil) if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol) raise TypeError, "Expected String or Symbol, got #{rpc_name.class}." end rpc_name = rpc_name.to_s api = api.to_s version = version || 'v1' service = self.discovered_api(api, version) if service.to_h[rpc_name] return service.to_h[rpc_name] else return nil end end |
#discovery_document(api, version = nil) ⇒ Hash
Returns the parsed discovery document.
354 355 356 357 358 359 360 361 362 363 364 365 |
# File 'lib/google/api_client.rb', line 354 def discovery_document(api, version=nil) api = api.to_s version = version || 'v1' return @discovery_documents["#{api}:#{version}"] ||= (begin response = self.execute!( :http_method => :get, :uri => self.discovery_uri(api, version), :authenticated => false ) response.data end) end |
#discovery_uri(api, version = nil) ⇒ Addressable::URI
Returns the URI for the discovery document.
295 296 297 298 299 300 301 302 303 304 305 |
# File 'lib/google/api_client.rb', line 295 def discovery_uri(api, version=nil) api = api.to_s version = version || 'v1' return @discovery_uris["#{api}:#{version}"] ||= ( resolve_uri( self.discovery_path + '/apis/{api}/{version}/rest', 'api' => api, 'version' => version ) ) end |
#execute(*params) ⇒ Object
Same as Google::APIClient#execute!, but does not raise an exception for normal API errros.
667 668 669 670 671 672 673 |
# File 'lib/google/api_client.rb', line 667 def execute(*params) begin return self.execute!(*params) rescue TransmissionError => e return e.result end end |
#execute!(*params) ⇒ Google::APIClient::Result
Executes a request, wrapping it in a Result object.
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 |
# File 'lib/google/api_client.rb', line 591 def execute!(*params) if params.first.kind_of?(Google::APIClient::Request) request = params.shift = params.shift || {} else # This block of code allows us to accept multiple parameter passing # styles, and maintaining some backwards compatibility. # # Note: I'm extremely tempted to deprecate this style of execute call. if params.last.respond_to?(:to_hash) && params.size == 1 = params.pop else = {} end [:api_method] = params.shift if params.size > 0 [:parameters] = params.shift if params.size > 0 [:body] = params.shift if params.size > 0 [:headers] = params.shift if params.size > 0 .update(params.shift) if params.size > 0 request = self.generate_request() end request.headers['User-Agent'] ||= '' + self.user_agent unless self.user_agent.nil? request.headers['Accept-Encoding'] ||= 'gzip' unless [:gzip] == false request.headers['Content-Type'] ||= '' request.parameters['key'] ||= self.key unless self.key.nil? request.parameters['userIp'] ||= self.user_ip unless self.user_ip.nil? connection = [:connection] || self.connection request. = [:authorization] || self. unless [:authenticated] == false tries = 1 + ([:retries] || self.retries) attempt = 0 Retriable.retriable :tries => tries, :on => [TransmissionError], :on_retry => client_error_handler, :interval => lambda {|attempts| (2 ** attempts) + rand} do attempt += 1 # This 2nd level retriable only catches auth errors, and supports 1 retry, which allows # auth to be re-attempted without having to retry all sorts of other failures like # NotFound, etc Retriable.retriable :tries => ((expired_auth_retry || tries > 1) && attempt == 1) ? 2 : 1, :on => [AuthorizationError], :on_retry => (request.) do result = request.send(connection, true) case result.status when 200...300 result when 301, 302, 303, 307 request = generate_request(request.to_hash.merge({ :uri => result.headers['location'], :api_method => nil })) raise RedirectError.new(result.headers['location'], result) when 401 raise AuthorizationError.new(result. || 'Invalid/Expired Authentication', result) when 400, 402...500 raise ClientError.new(result. || "A client error has occurred", result) when 500...600 raise ServerError.new(result. || "A server error has occurred", result) else raise TransmissionError.new(result. || "A transmission error has occurred", result) end end end end |
#generate_request(options = {}) ⇒ Google::APIClient::Reference
Generates a request.
542 543 544 545 546 547 |
# File 'lib/google/api_client.rb', line 542 def generate_request(={}) = { :api_client => self }.merge() return Google::APIClient::Request.new() end |
#preferred_version(api) ⇒ Google::APIClient::API
Warning: This method should be used with great care.
Returns the service object with the highest version number.
As APIs are updated, minor differences between versions may cause incompatibilities. Requesting a specific version will avoid this issue.
449 450 451 452 453 454 455 456 457 458 |
# File 'lib/google/api_client.rb', line 449 def preferred_version(api) if !api.kind_of?(String) && !api.kind_of?(Symbol) raise TypeError, "Expected String or Symbol, got #{api.class}." end api = api.to_s return self.discovered_apis.detect do |a| a.name == api && a.preferred == true end end |
#register_discovery_document(api, version, discovery_document) ⇒ Google::APIClient::API
Manually registers a pre-loaded discovery document for a specific version of an API.
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 |
# File 'lib/google/api_client.rb', line 316 def register_discovery_document(api, version, discovery_document) api = api.to_s version = version || 'v1' if discovery_document.kind_of?(StringIO) discovery_document.rewind discovery_document = discovery_document.string elsif discovery_document.respond_to?(:to_str) discovery_document = discovery_document.to_str else raise TypeError, "Expected String or StringIO, got #{discovery_document.class}." end @discovery_documents["#{api}:#{version}"] = MultiJson.load(discovery_document) discovered_api(api, version) end |
#register_discovery_uri(api, version, uri) ⇒ Google::APIClient::API
Manually registers a URI as a discovery document for a specific version of an API.
282 283 284 285 286 287 |
# File 'lib/google/api_client.rb', line 282 def register_discovery_uri(api, version, uri) api = api.to_s version = version || 'v1' @discovery_uris["#{api}:#{version}"] = uri discovered_api(api, version) end |
#verify_id_token! ⇒ Object
Use the google-id-token gem for verifying JWTs
Verifies an ID token against a server certificate. Used to ensure that an ID token supplied by an untrusted client-side mechanism is valid. Raises an error if the token is invalid or missing.
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 |
# File 'lib/google/api_client.rb', line 466 def verify_id_token! require 'jwt' require 'openssl' @certificates ||= {} if !self..respond_to?(:id_token) raise ArgumentError, ( "Current authorization mechanism does not support ID tokens: " + "#{self..class.to_s}" ) elsif !self..id_token raise ArgumentError, ( "Could not verify ID token, ID token missing. " + "Scopes were: #{self..scope.inspect}" ) else check_cached_certs = lambda do valid = false for key, cert in @certificates begin self..decoded_id_token(cert.public_key) valid = true rescue JWT::DecodeError, Signet::UnsafeOperationError # Expected exception. Ignore, ID token has not been validated. end end valid end if check_cached_certs.call() return true end response = self.execute!( :http_method => :get, :uri => 'https://www.googleapis.com/oauth2/v1/certs', :authenticated => false ) @certificates.merge!( Hash[MultiJson.load(response.body).map do |key, cert| [key, OpenSSL::X509::Certificate.new(cert)] end] ) if check_cached_certs.call() return true else raise InvalidIDTokenError, "Could not verify ID token against any available certificate." end end return nil end |