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.
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 142 143 144 145 146 147 |
# File 'lib/google/api_client.rb', line 87 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 if !['scope'].nil? and self..respond_to?(:scope=) self..scope = ['scope'] end 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.
153 154 155 |
# File 'lib/google/api_client.rb', line 153 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.
220 221 222 |
# File 'lib/google/api_client.rb', line 220 def auto_refresh_token @auto_refresh_token end |
#connection ⇒ Faraday::Connection
Default Faraday/HTTP connection.
213 214 215 |
# File 'lib/google/api_client.rb', line 213 def connection @connection end |
#discovery_path ⇒ String
The base path used by the client for discovery.
260 261 262 |
# File 'lib/google/api_client.rb', line 260 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
274 275 276 |
# File 'lib/google/api_client.rb', line 274 def expired_auth_retry @expired_auth_retry end |
#host ⇒ String
The API hostname used by the client.
246 247 248 |
# File 'lib/google/api_client.rb', line 246 def host @host end |
#key ⇒ String
The application's API key issued by the API console.
226 227 228 |
# File 'lib/google/api_client.rb', line 226 def key @key end |
#port ⇒ String
The port number used by the client.
253 254 255 |
# File 'lib/google/api_client.rb', line 253 def port @port end |
#retries ⇒ FixNum
Number of times to retry on recoverable errors
267 268 269 |
# File 'lib/google/api_client.rb', line 267 def retries @retries end |
#user_agent ⇒ String
The user agent used by the client.
239 240 241 |
# File 'lib/google/api_client.rb', line 239 def user_agent @user_agent end |
#user_ip ⇒ String
The IP address of the user this request is being performed on behalf of.
232 233 234 |
# File 'lib/google/api_client.rb', line 232 def user_ip @user_ip end |
Instance Method Details
#directory_document ⇒ Hash
Returns the parsed directory document.
347 348 349 350 351 352 353 354 355 356 |
# File 'lib/google/api_client.rb', line 347 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.
280 281 282 |
# File 'lib/google/api_client.rb', line 280 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.
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 |
# File 'lib/google/api_client.rb', line 404 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.
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 |
# File 'lib/google/api_client.rb', line 381 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.
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 |
# File 'lib/google/api_client.rb', line 433 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.
364 365 366 367 368 369 370 371 372 373 374 375 |
# File 'lib/google/api_client.rb', line 364 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.
305 306 307 308 309 310 311 312 313 314 315 |
# File 'lib/google/api_client.rb', line 305 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.
677 678 679 680 681 682 683 |
# File 'lib/google/api_client.rb', line 677 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.
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 661 662 663 664 665 666 667 668 669 670 |
# File 'lib/google/api_client.rb', line 601 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.
552 553 554 555 556 557 |
# File 'lib/google/api_client.rb', line 552 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.
459 460 461 462 463 464 465 466 467 468 |
# File 'lib/google/api_client.rb', line 459 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.
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 |
# File 'lib/google/api_client.rb', line 326 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.
292 293 294 295 296 297 |
# File 'lib/google/api_client.rb', line 292 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.
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 515 516 517 518 519 520 521 522 523 524 |
# File 'lib/google/api_client.rb', line 476 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 |