1 # Copyright 2010 Google Inc.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
17 require 'faraday/gzip'
19 require 'compat/multi_json'
23 require 'google/api_client/version'
24 require 'google/api_client/logging'
25 require 'google/api_client/errors'
26 require 'google/api_client/environment'
27 require 'google/api_client/discovery'
28 require 'google/api_client/request'
29 require 'google/api_client/reference'
30 require 'google/api_client/result'
31 require 'google/api_client/media'
32 require 'google/api_client/service_account'
33 require 'google/api_client/batch'
34 require 'google/api_client/charset'
35 require 'google/api_client/client_secrets'
36 require 'google/api_client/railtie' if defined?(Rails)
41 # This class manages APIs communication.
43 include Google::APIClient::Logging
46 # Creates a new Google API client.
48 # @param [Hash] options The configuration parameters for the client.
49 # @option options [Symbol, #generate_authenticated_request] :authorization
51 # The authorization mechanism used by the client. The following
52 # mechanisms are supported out-of-the-box:
54 # <li><code>:two_legged_oauth_1</code></li>
55 # <li><code>:oauth_1</code></li>
56 # <li><code>:oauth_2</code></li>
57 # <li><code>:google_app_default</code></li>
59 # @option options [Boolean] :auto_refresh_token (true)
60 # The setting that controls whether or not the api client attempts to
61 # refresh authorization when a 401 is hit in #execute. If the token does
62 # not support it, this option is ignored.
63 # @option options [String] :application_name
64 # The name of the application using the client.
65 # @option options [String | Array | nil] :scope
66 # The scope(s) used when using google application default credentials
67 # @option options [String] :application_version
68 # The version number of the application using the client.
69 # @option options [String] :user_agent
70 # ("{app_name} google-api-ruby-client/{version} {os_name}/{os_version}")
71 # The user agent used by the client. Most developers will want to
72 # leave this value alone and use the `:application_name` option instead.
73 # @option options [String] :host ("www.googleapis.com")
74 # The API hostname used by the client. This rarely needs to be changed.
75 # @option options [String] :port (443)
76 # The port number used by the client. This rarely needs to be changed.
77 # @option options [String] :discovery_path ("/discovery/v1")
78 # The discovery base path. This rarely needs to be changed.
79 # @option options [String] :ca_file
80 # Optional set of root certificates to use when validating SSL connections.
81 # By default, a bundled set of trusted roots will be used.
82 # @options options[Hash] :force_encoding
83 # Experimental option. True if response body should be force encoded into the charset
84 # specified in the Content-Type header. Mostly intended for compressed content.
85 # @options options[Hash] :faraday_options
86 # Pass through of options to set on the Faraday connection
87 def initialize(options={})
88 logger.debug { "#{self.class} - Initializing client with options #{options}" }
90 # Normalize key to String to allow indifferent access.
91 options = options.inject({}) do |accu, (key, value)|
92 accu[key.to_sym] = value
95 # Almost all API usage will have a host of 'www.googleapis.com'.
96 self.host = options[:host] || 'www.googleapis.com'
97 self.port = options[:port] || 443
98 self.discovery_path = options[:discovery_path] || '/discovery/v1'
100 # Most developers will want to leave this value alone and use the
101 # application_name option.
102 if options[:application_name]
103 app_name = options[:application_name]
104 app_version = options[:application_version]
105 application_string = "#{app_name}/#{app_version || '0.0.0'}"
107 logger.warn { "#{self.class} - Please provide :application_name and :application_version when initializing the client" }
110 proxy = options[:proxy] || Object::ENV["http_proxy"]
112 self.user_agent = options[:user_agent] || (
113 "#{application_string} " +
114 "google-api-ruby-client/#{Google::APIClient::VERSION::STRING} #{ENV::OS_VERSION}".strip + " (gzip)"
116 # The writer method understands a few Symbols and will generate useful
117 # default authentication mechanisms.
119 options.key?(:authorization) ? options[:authorization] : :oauth_2
120 if !options['scope'].nil? and self.authorization.respond_to?(:scope=)
121 self.authorization.scope = options['scope']
123 self.auto_refresh_token = options.fetch(:auto_refresh_token) { true }
124 self.key = options[:key]
125 self.user_ip = options[:user_ip]
126 self.retries = options.fetch(:retries) { 0 }
127 self.expired_auth_retry = options.fetch(:expired_auth_retry) { true }
129 @discovery_documents = {}
130 @discovered_apis = {}
131 ca_file = options[:ca_file] || File.expand_path('../../cacerts.pem', __FILE__)
132 self.connection = Faraday.new do |faraday|
133 faraday.request :gzip
134 faraday.response :charset if options[:force_encoding]
135 faraday.options.params_encoder = Faraday::FlatParamsEncoder
136 faraday.ssl.ca_file = ca_file
137 faraday.ssl.verify = true
138 if faraday.respond_to?(:proxy=)
140 faraday.proxy = proxy
142 # older versions of faraday
145 faraday.adapter Faraday.default_adapter
146 if options[:faraday_option].is_a?(Hash)
147 options[:faraday_option].each_pair do |option, value|
148 faraday.options.send("#{option}=", value)
156 # Returns the authorization mechanism used by the client.
158 # @return [#generate_authenticated_request] The authorization mechanism.
159 attr_reader :authorization
162 # Sets the authorization mechanism used by the client.
164 # @param [#generate_authenticated_request] new_authorization
165 # The new authorization mechanism.
166 def authorization=(new_authorization)
167 case new_authorization
168 when :oauth_1, :oauth
169 require 'signet/oauth_1/client'
170 # NOTE: Do not rely on this default value, as it may change
171 new_authorization = Signet::OAuth1::Client.new(
172 :temporary_credential_uri =>
173 'https://www.google.com/accounts/OAuthGetRequestToken',
174 :authorization_uri =>
175 'https://www.google.com/accounts/OAuthAuthorizeToken',
176 :token_credential_uri =>
177 'https://www.google.com/accounts/OAuthGetAccessToken',
178 :client_credential_key => 'anonymous',
179 :client_credential_secret => 'anonymous'
181 when :two_legged_oauth_1, :two_legged_oauth
182 require 'signet/oauth_1/client'
183 # NOTE: Do not rely on this default value, as it may change
184 new_authorization = Signet::OAuth1::Client.new(
185 :client_credential_key => nil,
186 :client_credential_secret => nil,
189 when :google_app_default
191 new_authorization = Google::Auth.get_application_default
194 require 'signet/oauth_2/client'
195 # NOTE: Do not rely on this default value, as it may change
196 new_authorization = Signet::OAuth2::Client.new(
197 :authorization_uri =>
198 'https://accounts.google.com/o/oauth2/auth',
199 :token_credential_uri =>
200 'https://accounts.google.com/o/oauth2/token'
203 # No authorization mechanism
205 if !new_authorization.respond_to?(:generate_authenticated_request)
207 'Expected authorization mechanism to respond to ' +
208 '#generate_authenticated_request.'
211 @authorization = new_authorization
212 return @authorization
216 # Default Faraday/HTTP connection.
218 # @return [Faraday::Connection]
219 attr_accessor :connection
222 # The setting that controls whether or not the api client attempts to
223 # refresh authorization when a 401 is hit in #execute.
226 attr_accessor :auto_refresh_token
229 # The application's API key issued by the API console.
231 # @return [String] The API key.
235 # The IP address of the user this request is being performed on behalf of.
237 # @return [String] The user's IP address.
238 attr_accessor :user_ip
241 # The user agent used by the client.
244 # The user agent string used in the User-Agent header.
245 attr_accessor :user_agent
248 # The API hostname used by the client.
251 # The API hostname. Should almost always be 'www.googleapis.com'.
255 # The port number used by the client.
258 # The port number. Should almost always be 443.
262 # The base path used by the client for discovery.
265 # The base path. Should almost always be '/discovery/v1'.
266 attr_accessor :discovery_path
269 # Number of times to retry on recoverable errors
273 attr_accessor :retries
276 # Whether or not an expired auth token should be re-acquired
277 # (and the operation retried) regardless of retries setting
279 # Auto retry on auth expiry
280 attr_accessor :expired_auth_retry
283 # Returns the URI for the directory document.
285 # @return [Addressable::URI] The URI of the directory document.
287 return resolve_uri(self.discovery_path + '/apis')
291 # Manually registers a URI as a discovery document for a specific version
294 # @param [String, Symbol] api The API name.
295 # @param [String] version The desired version of the API.
296 # @param [Addressable::URI] uri The URI of the discovery document.
297 # @return [Google::APIClient::API] The service object.
298 def register_discovery_uri(api, version, uri)
300 version = version || 'v1'
301 @discovery_uris["#{api}:#{version}"] = uri
302 discovered_api(api, version)
306 # Returns the URI for the discovery document.
308 # @param [String, Symbol] api The API name.
309 # @param [String] version The desired version of the API.
310 # @return [Addressable::URI] The URI of the discovery document.
311 def discovery_uri(api, version=nil)
313 version = version || 'v1'
314 return @discovery_uris["#{api}:#{version}"] ||= (
316 self.discovery_path + '/apis/{api}/{version}/rest',
324 # Manually registers a pre-loaded discovery document for a specific version
327 # @param [String, Symbol] api The API name.
328 # @param [String] version The desired version of the API.
329 # @param [String, StringIO] discovery_document
330 # The contents of the discovery document.
331 # @return [Google::APIClient::API] The service object.
332 def register_discovery_document(api, version, discovery_document)
334 version = version || 'v1'
335 if discovery_document.kind_of?(StringIO)
336 discovery_document.rewind
337 discovery_document = discovery_document.string
338 elsif discovery_document.respond_to?(:to_str)
339 discovery_document = discovery_document.to_str
342 "Expected String or StringIO, got #{discovery_document.class}."
344 @discovery_documents["#{api}:#{version}"] =
345 MultiJson.load(discovery_document)
346 discovered_api(api, version)
350 # Returns the parsed directory document.
352 # @return [Hash] The parsed JSON from the directory document.
353 def directory_document
354 return @directory_document ||= (begin
355 response = self.execute!(
356 :http_method => :get,
357 :uri => self.directory_uri,
358 :authenticated => false
365 # Returns the parsed discovery document.
367 # @param [String, Symbol] api The API name.
368 # @param [String] version The desired version of the API.
369 # @return [Hash] The parsed JSON from the discovery document.
370 def discovery_document(api, version=nil)
372 version = version || 'v1'
373 return @discovery_documents["#{api}:#{version}"] ||= (begin
374 response = self.execute!(
375 :http_method => :get,
376 :uri => self.discovery_uri(api, version),
377 :authenticated => false
384 # Returns all APIs published in the directory document.
386 # @return [Array] The list of available APIs.
388 @directory_apis ||= (begin
389 document_base = self.directory_uri
390 if self.directory_document && self.directory_document['items']
391 self.directory_document['items'].map do |discovery_document|
392 Google::APIClient::API.new(
404 # Returns the service object for a given service name and service version.
406 # @param [String, Symbol] api The API name.
407 # @param [String] version The desired version of the API.
409 # @return [Google::APIClient::API] The service object.
410 def discovered_api(api, version=nil)
411 if !api.kind_of?(String) && !api.kind_of?(Symbol)
413 "Expected String or Symbol, got #{api.class}."
416 version = version || 'v1'
417 return @discovered_apis["#{api}:#{version}"] ||= begin
418 document_base = self.discovery_uri(api, version)
419 discovery_document = self.discovery_document(api, version)
420 if document_base && discovery_document
421 Google::APIClient::API.new(
432 # Returns the method object for a given RPC name and service version.
434 # @param [String, Symbol] rpc_name The RPC name of the desired method.
435 # @param [String, Symbol] api The API the method is within.
436 # @param [String] version The desired version of the API.
438 # @return [Google::APIClient::Method] The method object.
439 def discovered_method(rpc_name, api, version=nil)
440 if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
442 "Expected String or Symbol, got #{rpc_name.class}."
444 rpc_name = rpc_name.to_s
446 version = version || 'v1'
447 service = self.discovered_api(api, version)
448 if service.to_h[rpc_name]
449 return service.to_h[rpc_name]
456 # Returns the service object with the highest version number.
458 # @note <em>Warning</em>: This method should be used with great care.
459 # As APIs are updated, minor differences between versions may cause
460 # incompatibilities. Requesting a specific version will avoid this issue.
462 # @param [String, Symbol] api The name of the service.
464 # @return [Google::APIClient::API] The service object.
465 def preferred_version(api)
466 if !api.kind_of?(String) && !api.kind_of?(Symbol)
468 "Expected String or Symbol, got #{api.class}."
471 return self.discovered_apis.detect do |a|
472 a.name == api && a.preferred == true
477 # Verifies an ID token against a server certificate. Used to ensure that
478 # an ID token supplied by an untrusted client-side mechanism is valid.
479 # Raises an error if the token is invalid or missing.
481 # @deprecated Use the google-id-token gem for verifying JWTs
486 if !self.authorization.respond_to?(:id_token)
487 raise ArgumentError, (
488 "Current authorization mechanism does not support ID tokens: " +
489 "#{self.authorization.class.to_s}"
491 elsif !self.authorization.id_token
492 raise ArgumentError, (
493 "Could not verify ID token, ID token missing. " +
494 "Scopes were: #{self.authorization.scope.inspect}"
497 check_cached_certs = lambda do
499 for _key, cert in @certificates
501 self.authorization.decoded_id_token(cert.public_key)
503 rescue JWT::DecodeError, Signet::UnsafeOperationError
504 # Expected exception. Ignore, ID token has not been validated.
509 if check_cached_certs.call()
512 response = self.execute!(
513 :http_method => :get,
514 :uri => 'https://www.googleapis.com/oauth2/v1/certs',
515 :authenticated => false
517 @certificates.merge!(
518 Hash[MultiJson.load(response.body).map do |key, cert|
519 [key, OpenSSL::X509::Certificate.new(cert)]
522 if check_cached_certs.call()
525 raise InvalidIDTokenError,
526 "Could not verify ID token against any available certificate."
533 # Generates a request.
535 # @option options [Google::APIClient::Method] :api_method
536 # The method object or the RPC name of the method being executed.
537 # @option options [Hash, Array] :parameters
538 # The parameters to send to the method.
539 # @option options [Hash, Array] :headers The HTTP headers for the request.
540 # @option options [String] :body The body of the request.
541 # @option options [String] :version ("v1")
542 # The service version. Only used if `api_method` is a `String`.
543 # @option options [#generate_authenticated_request] :authorization
544 # The authorization mechanism for the response. Used only if
545 # `:authenticated` is `true`.
546 # @option options [TrueClass, FalseClass] :authenticated (true)
547 # `true` if the request must be signed or somehow
548 # authenticated, `false` otherwise.
550 # @return [Google::APIClient::Reference] The generated request.
553 # request = client.generate_request(
554 # :api_method => 'plus.activities.list',
556 # {'collection' => 'public', 'userId' => 'me'}
558 def generate_request(options={})
562 return Google::APIClient::Request.new(options)
566 # Executes a request, wrapping it in a Result object.
568 # @param [Google::APIClient::Request, Hash, Array] params
569 # Either a Google::APIClient::Request, a Hash, or an Array.
571 # If a Google::APIClient::Request, no other parameters are expected.
573 # If a Hash, the below parameters are handled. If an Array, the
574 # parameters are assumed to be in the below order:
576 # - (Google::APIClient::Method) api_method:
577 # The method object or the RPC name of the method being executed.
578 # - (Hash, Array) parameters:
579 # The parameters to send to the method.
580 # - (String) body: The body of the request.
581 # - (Hash, Array) headers: The HTTP headers for the request.
582 # - (Hash) options: A set of options for the request, of which:
583 # - (#generate_authenticated_request) :authorization (default: true) -
584 # The authorization mechanism for the response. Used only if
585 # `:authenticated` is `true`.
586 # - (TrueClass, FalseClass) :authenticated (default: true) -
587 # `true` if the request must be signed or somehow
588 # authenticated, `false` otherwise.
589 # - (TrueClass, FalseClass) :gzip (default: true) -
590 # `true` if gzip enabled, `false` otherwise.
591 # - (FixNum) :retries -
592 # # of times to retry on recoverable errors
594 # @return [Google::APIClient::Result] The result from the API, nil if batch.
597 # result = client.execute(batch_request)
600 # plus = client.discovered_api('plus')
601 # result = client.execute(
602 # :api_method => plus.activities.list,
603 # :parameters => {'collection' => 'public', 'userId' => 'me'}
606 # @see Google::APIClient#generate_request
607 def execute!(*params)
608 if params.first.kind_of?(Google::APIClient::Request)
609 request = params.shift
610 options = params.shift || {}
612 # This block of code allows us to accept multiple parameter passing
613 # styles, and maintaining some backwards compatibility.
615 # Note: I'm extremely tempted to deprecate this style of execute call.
616 if params.last.respond_to?(:to_hash) && params.size == 1
622 options[:api_method] = params.shift if params.size > 0
623 options[:parameters] = params.shift if params.size > 0
624 options[:body] = params.shift if params.size > 0
625 options[:headers] = params.shift if params.size > 0
626 options.update(params.shift) if params.size > 0
627 request = self.generate_request(options)
630 request.headers['User-Agent'] ||= '' + self.user_agent unless self.user_agent.nil?
631 request.headers['Accept-Encoding'] ||= 'gzip' unless options[:gzip] == false
632 request.headers['Content-Type'] ||= ''
633 request.parameters['key'] ||= self.key unless self.key.nil?
634 request.parameters['userIp'] ||= self.user_ip unless self.user_ip.nil?
636 connection = options[:connection] || self.connection
637 request.authorization = options[:authorization] || self.authorization unless options[:authenticated] == false
639 tries = 1 + (options[:retries] || self.retries)
642 Retriable.retriable :tries => tries,
643 :on => [TransmissionError],
644 :on_retry => client_error_handler,
645 :interval => lambda {|attempts| (2 ** attempts) + rand} do
648 # This 2nd level retriable only catches auth errors, and supports 1 retry, which allows
649 # auth to be re-attempted without having to retry all sorts of other failures like
651 Retriable.retriable :tries => ((expired_auth_retry || tries > 1) && attempt == 1) ? 2 : 1,
652 :on => [AuthorizationError],
653 :on_retry => authorization_error_handler(request.authorization) do
654 result = request.send(connection, true)
659 when 301, 302, 303, 307
660 request = generate_request(request.to_hash.merge({
661 :uri => result.headers['location'],
664 raise RedirectError.new(result.headers['location'], result)
666 raise AuthorizationError.new(result.error_message || 'Invalid/Expired Authentication', result)
668 raise ClientError.new(result.error_message || "A client error has occurred", result)
670 raise ServerError.new(result.error_message || "A server error has occurred", result)
672 raise TransmissionError.new(result.error_message || "A transmission error has occurred", result)
679 # Same as Google::APIClient#execute!, but does not raise an exception for
682 # @see Google::APIClient#execute
685 return self.execute!(*params)
686 rescue TransmissionError => e
694 # Resolves a URI template against the client's configured base.
697 # @param [String, Addressable::URI, Addressable::Template] template
698 # The template to resolve.
699 # @param [Hash] mapping The mapping that corresponds to the template.
700 # @return [Addressable::URI] The expanded URI.
701 def resolve_uri(template, mapping={})
702 @base_uri ||= Addressable::URI.new(
707 template = if template.kind_of?(Addressable::Template)
709 elsif template.respond_to?(:to_str)
713 "Expected String, Addressable::URI, or Addressable::Template, " +
714 "got #{template.class}."
716 return Addressable::Template.new(@base_uri + template).expand(mapping)
721 # Returns on proc for special processing of retries for authorization errors
722 # Only 401s should be retried and only if the credentials are refreshable
724 # @param [#fetch_access_token!] authorization
725 # OAuth 2 credentials
727 def authorization_error_handler(authorization)
728 can_refresh = authorization.respond_to?(:refresh_token) && auto_refresh_token
729 Proc.new do |exception, tries|
730 next unless exception.kind_of?(AuthorizationError)
733 logger.debug("Attempting refresh of access token & retry of request")
734 authorization.fetch_access_token!
736 rescue Signet::AuthorizationError
744 # Returns on proc for special processing of retries as not all client errors
745 # are recoverable. Only 401s should be retried (via authorization_error_handler)
748 def client_error_handler
749 Proc.new do |exception, tries|
750 raise exception if exception.kind_of?(ClientError)