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.
18 require 'compat/multi_json'
22 require 'google/api_client/version'
23 require 'google/api_client/logging'
24 require 'google/api_client/errors'
25 require 'google/api_client/environment'
26 require 'google/api_client/discovery'
27 require 'google/api_client/request'
28 require 'google/api_client/reference'
29 require 'google/api_client/result'
30 require 'google/api_client/media'
31 require 'google/api_client/service_account'
32 require 'google/api_client/batch'
33 require 'google/api_client/gzip'
34 require 'google/api_client/client_secrets'
35 require 'google/api_client/railtie' if defined?(Rails)
40 # This class manages APIs communication.
42 include Google::APIClient::Logging
45 # Creates a new Google API client.
47 # @param [Hash] options The configuration parameters for the client.
48 # @option options [Symbol, #generate_authenticated_request] :authorization
50 # The authorization mechanism used by the client. The following
51 # mechanisms are supported out-of-the-box:
53 # <li><code>:two_legged_oauth_1</code></li>
54 # <li><code>:oauth_1</code></li>
55 # <li><code>:oauth_2</code></li>
57 # @option options [Boolean] :auto_refresh_token (true)
58 # The setting that controls whether or not the api client attempts to
59 # refresh authorization when a 401 is hit in #execute. If the token does
60 # not support it, this option is ignored.
61 # @option options [String] :application_name
62 # The name of the application using the client.
63 # @option options [String] :application_version
64 # The version number of the application using the client.
65 # @option options [String] :user_agent
66 # ("{app_name} google-api-ruby-client/{version} {os_name}/{os_version}")
67 # The user agent used by the client. Most developers will want to
68 # leave this value alone and use the `:application_name` option instead.
69 # @option options [String] :host ("www.googleapis.com")
70 # The API hostname used by the client. This rarely needs to be changed.
71 # @option options [String] :port (443)
72 # The port number used by the client. This rarely needs to be changed.
73 # @option options [String] :discovery_path ("/discovery/v1")
74 # The discovery base path. This rarely needs to be changed.
75 # @option options [String] :ca_file
76 # Optional set of root certificates to use when validating SSL connections.
77 # By default, a bundled set of trusted roots will be used.
78 # @options options[Hash] :faraday_options
79 # Pass through of options to set on the Faraday connection
80 def initialize(options={})
81 logger.debug { "#{self.class} - Initializing client with options #{options}" }
83 # Normalize key to String to allow indifferent access.
84 options = options.inject({}) do |accu, (key, value)|
85 accu[key.to_sym] = value
88 # Almost all API usage will have a host of 'www.googleapis.com'.
89 self.host = options[:host] || 'www.googleapis.com'
90 self.port = options[:port] || 443
91 self.discovery_path = options[:discovery_path] || '/discovery/v1'
93 # Most developers will want to leave this value alone and use the
94 # application_name option.
95 if options[:application_name]
96 app_name = options[:application_name]
97 app_version = options[:application_version]
98 application_string = "#{app_name}/#{app_version || '0.0.0'}"
100 logger.warn { "#{self.class} - Please provide :application_name and :application_version when initializing the client" }
103 proxy = options[:proxy] || Object::ENV["http_proxy"]
105 self.user_agent = options[:user_agent] || (
106 "#{application_string} " +
107 "google-api-ruby-client/#{Google::APIClient::VERSION::STRING} #{ENV::OS_VERSION} (gzip)"
109 # The writer method understands a few Symbols and will generate useful
110 # default authentication mechanisms.
112 options.key?(:authorization) ? options[:authorization] : :oauth_2
113 self.auto_refresh_token = options.fetch(:auto_refresh_token) { true }
114 self.key = options[:key]
115 self.user_ip = options[:user_ip]
116 self.retries = options.fetch(:retries) { 0 }
118 @discovery_documents = {}
119 @discovered_apis = {}
120 ca_file = options[:ca_file] || File.expand_path('../../cacerts.pem', __FILE__)
121 self.connection = Faraday.new do |faraday|
122 faraday.response :gzip
123 faraday.options.params_encoder = Faraday::FlatParamsEncoder
124 faraday.ssl.ca_file = ca_file
125 faraday.ssl.verify = true
127 faraday.adapter Faraday.default_adapter
128 if options[:faraday_option].is_a?(Hash)
129 options[:faraday_option].each_pair do |option, value|
130 faraday.options.send("#{option}=", value)
138 # Returns the authorization mechanism used by the client.
140 # @return [#generate_authenticated_request] The authorization mechanism.
141 attr_reader :authorization
144 # Sets the authorization mechanism used by the client.
146 # @param [#generate_authenticated_request] new_authorization
147 # The new authorization mechanism.
148 def authorization=(new_authorization)
149 case new_authorization
150 when :oauth_1, :oauth
151 require 'signet/oauth_1/client'
152 # NOTE: Do not rely on this default value, as it may change
153 new_authorization = Signet::OAuth1::Client.new(
154 :temporary_credential_uri =>
155 'https://www.google.com/accounts/OAuthGetRequestToken',
156 :authorization_uri =>
157 'https://www.google.com/accounts/OAuthAuthorizeToken',
158 :token_credential_uri =>
159 'https://www.google.com/accounts/OAuthGetAccessToken',
160 :client_credential_key => 'anonymous',
161 :client_credential_secret => 'anonymous'
163 when :two_legged_oauth_1, :two_legged_oauth
164 require 'signet/oauth_1/client'
165 # NOTE: Do not rely on this default value, as it may change
166 new_authorization = Signet::OAuth1::Client.new(
167 :client_credential_key => nil,
168 :client_credential_secret => nil,
172 require 'signet/oauth_2/client'
173 # NOTE: Do not rely on this default value, as it may change
174 new_authorization = Signet::OAuth2::Client.new(
175 :authorization_uri =>
176 'https://accounts.google.com/o/oauth2/auth',
177 :token_credential_uri =>
178 'https://accounts.google.com/o/oauth2/token'
181 # No authorization mechanism
183 if !new_authorization.respond_to?(:generate_authenticated_request)
185 'Expected authorization mechanism to respond to ' +
186 '#generate_authenticated_request.'
189 @authorization = new_authorization
190 return @authorization
194 # Default Faraday/HTTP connection.
196 # @return [Faraday::Connection]
197 attr_accessor :connection
200 # The setting that controls whether or not the api client attempts to
201 # refresh authorization when a 401 is hit in #execute.
204 attr_accessor :auto_refresh_token
207 # The application's API key issued by the API console.
209 # @return [String] The API key.
213 # The IP address of the user this request is being performed on behalf of.
215 # @return [String] The user's IP address.
216 attr_accessor :user_ip
219 # The user agent used by the client.
222 # The user agent string used in the User-Agent header.
223 attr_accessor :user_agent
226 # The API hostname used by the client.
229 # The API hostname. Should almost always be 'www.googleapis.com'.
233 # The port number used by the client.
236 # The port number. Should almost always be 443.
240 # The base path used by the client for discovery.
243 # The base path. Should almost always be '/discovery/v1'.
244 attr_accessor :discovery_path
247 # Number of times to retry on recoverable errors
251 attr_accessor :retries
254 # Returns the URI for the directory document.
256 # @return [Addressable::URI] The URI of the directory document.
258 return resolve_uri(self.discovery_path + '/apis')
262 # Manually registers a URI as a discovery document for a specific version
265 # @param [String, Symbol] api The API name.
266 # @param [String] version The desired version of the API.
267 # @param [Addressable::URI] uri The URI of the discovery document.
268 def register_discovery_uri(api, version, uri)
270 version = version || 'v1'
271 @discovery_uris["#{api}:#{version}"] = uri
275 # Returns the URI for the discovery document.
277 # @param [String, Symbol] api The API name.
278 # @param [String] version The desired version of the API.
279 # @return [Addressable::URI] The URI of the discovery document.
280 def discovery_uri(api, version=nil)
282 version = version || 'v1'
283 return @discovery_uris["#{api}:#{version}"] ||= (
285 self.discovery_path + '/apis/{api}/{version}/rest',
293 # Manually registers a pre-loaded discovery document for a specific version
296 # @param [String, Symbol] api The API name.
297 # @param [String] version The desired version of the API.
298 # @param [String, StringIO] discovery_document
299 # The contents of the discovery document.
300 def register_discovery_document(api, version, discovery_document)
302 version = version || 'v1'
303 if discovery_document.kind_of?(StringIO)
304 discovery_document.rewind
305 discovery_document = discovery_document.string
306 elsif discovery_document.respond_to?(:to_str)
307 discovery_document = discovery_document.to_str
310 "Expected String or StringIO, got #{discovery_document.class}."
312 @discovery_documents["#{api}:#{version}"] =
313 MultiJson.load(discovery_document)
317 # Returns the parsed directory document.
319 # @return [Hash] The parsed JSON from the directory document.
320 def directory_document
321 return @directory_document ||= (begin
322 response = self.execute!(
323 :http_method => :get,
324 :uri => self.directory_uri,
325 :authenticated => false
332 # Returns the parsed discovery document.
334 # @param [String, Symbol] api The API name.
335 # @param [String] version The desired version of the API.
336 # @return [Hash] The parsed JSON from the discovery document.
337 def discovery_document(api, version=nil)
339 version = version || 'v1'
340 return @discovery_documents["#{api}:#{version}"] ||= (begin
341 response = self.execute!(
342 :http_method => :get,
343 :uri => self.discovery_uri(api, version),
344 :authenticated => false
351 # Returns all APIs published in the directory document.
353 # @return [Array] The list of available APIs.
355 @directory_apis ||= (begin
356 document_base = self.directory_uri
357 if self.directory_document && self.directory_document['items']
358 self.directory_document['items'].map do |discovery_document|
359 Google::APIClient::API.new(
371 # Returns the service object for a given service name and service version.
373 # @param [String, Symbol] api The API name.
374 # @param [String] version The desired version of the API.
376 # @return [Google::APIClient::API] The service object.
377 def discovered_api(api, version=nil)
378 if !api.kind_of?(String) && !api.kind_of?(Symbol)
380 "Expected String or Symbol, got #{api.class}."
383 version = version || 'v1'
384 return @discovered_apis["#{api}:#{version}"] ||= begin
385 document_base = self.discovery_uri(api, version)
386 discovery_document = self.discovery_document(api, version)
387 if document_base && discovery_document
388 Google::APIClient::API.new(
399 # Returns the method object for a given RPC name and service version.
401 # @param [String, Symbol] rpc_name The RPC name of the desired method.
402 # @param [String, Symbol] api The API the method is within.
403 # @param [String] version The desired version of the API.
405 # @return [Google::APIClient::Method] The method object.
406 def discovered_method(rpc_name, api, version=nil)
407 if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
409 "Expected String or Symbol, got #{rpc_name.class}."
411 rpc_name = rpc_name.to_s
413 version = version || 'v1'
414 service = self.discovered_api(api, version)
415 if service.to_h[rpc_name]
416 return service.to_h[rpc_name]
423 # Returns the service object with the highest version number.
425 # @note <em>Warning</em>: This method should be used with great care.
426 # As APIs are updated, minor differences between versions may cause
427 # incompatibilities. Requesting a specific version will avoid this issue.
429 # @param [String, Symbol] api The name of the service.
431 # @return [Google::APIClient::API] The service object.
432 def preferred_version(api)
433 if !api.kind_of?(String) && !api.kind_of?(Symbol)
435 "Expected String or Symbol, got #{api.class}."
438 return self.discovered_apis.detect do |a|
439 a.name == api && a.preferred == true
444 # Verifies an ID token against a server certificate. Used to ensure that
445 # an ID token supplied by an untrusted client-side mechanism is valid.
446 # Raises an error if the token is invalid or missing.
448 # @deprecated Use the google-id-token gem for verifying JWTs
453 if !self.authorization.respond_to?(:id_token)
454 raise ArgumentError, (
455 "Current authorization mechanism does not support ID tokens: " +
456 "#{self.authorization.class.to_s}"
458 elsif !self.authorization.id_token
459 raise ArgumentError, (
460 "Could not verify ID token, ID token missing. " +
461 "Scopes were: #{self.authorization.scope.inspect}"
464 check_cached_certs = lambda do
466 for key, cert in @certificates
468 self.authorization.decoded_id_token(cert.public_key)
470 rescue JWT::DecodeError, Signet::UnsafeOperationError
471 # Expected exception. Ignore, ID token has not been validated.
476 if check_cached_certs.call()
479 response = self.execute!(
480 :http_method => :get,
481 :uri => 'https://www.googleapis.com/oauth2/v1/certs',
482 :authenticated => false
484 @certificates.merge!(
485 Hash[MultiJson.load(response.body).map do |key, cert|
486 [key, OpenSSL::X509::Certificate.new(cert)]
489 if check_cached_certs.call()
492 raise InvalidIDTokenError,
493 "Could not verify ID token against any available certificate."
500 # Generates a request.
502 # @option options [Google::APIClient::Method] :api_method
503 # The method object or the RPC name of the method being executed.
504 # @option options [Hash, Array] :parameters
505 # The parameters to send to the method.
506 # @option options [Hash, Array] :headers The HTTP headers for the request.
507 # @option options [String] :body The body of the request.
508 # @option options [String] :version ("v1")
509 # The service version. Only used if `api_method` is a `String`.
510 # @option options [#generate_authenticated_request] :authorization
511 # The authorization mechanism for the response. Used only if
512 # `:authenticated` is `true`.
513 # @option options [TrueClass, FalseClass] :authenticated (true)
514 # `true` if the request must be signed or somehow
515 # authenticated, `false` otherwise.
517 # @return [Google::APIClient::Reference] The generated request.
520 # request = client.generate_request(
521 # :api_method => 'plus.activities.list',
523 # {'collection' => 'public', 'userId' => 'me'}
525 def generate_request(options={})
529 return Google::APIClient::Request.new(options)
533 # Executes a request, wrapping it in a Result object.
535 # @param [Google::APIClient::Request, Hash, Array] params
536 # Either a Google::APIClient::Request, a Hash, or an Array.
538 # If a Google::APIClient::Request, no other parameters are expected.
540 # If a Hash, the below parameters are handled. If an Array, the
541 # parameters are assumed to be in the below order:
543 # - (Google::APIClient::Method) api_method:
544 # The method object or the RPC name of the method being executed.
545 # - (Hash, Array) parameters:
546 # The parameters to send to the method.
547 # - (String) body: The body of the request.
548 # - (Hash, Array) headers: The HTTP headers for the request.
549 # - (Hash) options: A set of options for the request, of which:
550 # - (#generate_authenticated_request) :authorization (default: true) -
551 # The authorization mechanism for the response. Used only if
552 # `:authenticated` is `true`.
553 # - (TrueClass, FalseClass) :authenticated (default: true) -
554 # `true` if the request must be signed or somehow
555 # authenticated, `false` otherwise.
556 # - (TrueClass, FalseClass) :gzip (default: true) -
557 # `true` if gzip enabled, `false` otherwise.
558 # - (FixNum) :retries -
559 # # of times to retry on recoverable errors
561 # @return [Google::APIClient::Result] The result from the API, nil if batch.
564 # result = client.execute(batch_request)
567 # plus = client.discovered_api('plus')
568 # result = client.execute(
569 # :api_method => plus.activities.list,
570 # :parameters => {'collection' => 'public', 'userId' => 'me'}
573 # @see Google::APIClient#generate_request
574 def execute!(*params)
575 if params.first.kind_of?(Google::APIClient::Request)
576 request = params.shift
577 options = params.shift || {}
579 # This block of code allows us to accept multiple parameter passing
580 # styles, and maintaining some backwards compatibility.
582 # Note: I'm extremely tempted to deprecate this style of execute call.
583 if params.last.respond_to?(:to_hash) && params.size == 1
589 options[:api_method] = params.shift if params.size > 0
590 options[:parameters] = params.shift if params.size > 0
591 options[:body] = params.shift if params.size > 0
592 options[:headers] = params.shift if params.size > 0
593 options.update(params.shift) if params.size > 0
594 request = self.generate_request(options)
597 request.headers['User-Agent'] ||= '' + self.user_agent unless self.user_agent.nil?
598 request.headers['Accept-Encoding'] ||= 'gzip' unless options[:gzip] == false
599 request.headers['Content-Type'] ||= ''
600 request.parameters['key'] ||= self.key unless self.key.nil?
601 request.parameters['userIp'] ||= self.user_ip unless self.user_ip.nil?
603 connection = options[:connection] || self.connection
604 request.authorization = options[:authorization] || self.authorization unless options[:authenticated] == false
606 tries = 1 + (options[:retries] || self.retries)
608 Retriable.retriable :tries => tries,
609 :on => [TransmissionError],
610 :on_retry => client_error_handler(request.authorization),
611 :interval => lambda {|attempts| (2 ** attempts) + rand} do
612 result = request.send(connection, true)
617 when 301, 302, 303, 307
618 request = generate_request(request.to_hash.merge({
619 :uri => result.headers['location'],
622 raise RedirectError.new(result.headers['location'], result)
624 raise ClientError.new(result.error_message || "A client error has occurred", result)
626 raise ServerError.new(result.error_message || "A server error has occurred", result)
628 raise TransmissionError.new(result.error_message || "A transmission error has occurred", result)
634 # Same as Google::APIClient#execute!, but does not raise an exception for
637 # @see Google::APIClient#execute
640 return self.execute!(*params)
641 rescue TransmissionError => e
649 # Resolves a URI template against the client's configured base.
652 # @param [String, Addressable::URI, Addressable::Template] template
653 # The template to resolve.
654 # @param [Hash] mapping The mapping that corresponds to the template.
655 # @return [Addressable::URI] The expanded URI.
656 def resolve_uri(template, mapping={})
657 @base_uri ||= Addressable::URI.new(
662 template = if template.kind_of?(Addressable::Template)
664 elsif template.respond_to?(:to_str)
668 "Expected String, Addressable::URI, or Addressable::Template, " +
669 "got #{template.class}."
671 return Addressable::Template.new(@base_uri + template).expand(mapping)
676 # Returns on proc for special processing of retries as not all client errors
677 # are recoverable. Only 401s should be retried and only if the credentials
680 # @param [#fetch_access_token!] authorization
681 # OAuth 2 credentials
683 def client_error_handler(authorization)
684 can_refresh = authorization.respond_to?(:refresh_token) && auto_refresh_token
685 Proc.new do |exception, tries|
686 next unless exception.kind_of?(ClientError)
687 if exception.result.status == 401 && can_refresh && tries == 1
689 logger.debug("Attempting refresh of access token & retry of request")
690 authorization.fetch_access_token!
692 rescue Signet::AuthorizationError