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::Railtie)
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 def initialize(options={})
79 logger.debug { "#{self.class} - Initializing client with options #{options}" }
81 # Normalize key to String to allow indifferent access.
82 options = options.inject({}) do |accu, (key, value)|
83 accu[key.to_sym] = value
86 # Almost all API usage will have a host of 'www.googleapis.com'.
87 self.host = options[:host] || 'www.googleapis.com'
88 self.port = options[:port] || 443
89 self.discovery_path = options[:discovery_path] || '/discovery/v1'
91 # Most developers will want to leave this value alone and use the
92 # application_name option.
93 if options[:application_name]
94 app_name = options[:application_name]
95 app_version = options[:application_version]
96 application_string = "#{app_name}/#{app_version || '0.0.0'}"
98 logger.warn { "#{self.class} - Please provide :application_name and :application_version when initializing the client" }
101 proxy = options[:proxy] || Object::ENV["http_proxy"]
103 self.user_agent = options[:user_agent] || (
104 "#{application_string} " +
105 "google-api-ruby-client/#{Google::APIClient::VERSION::STRING} #{ENV::OS_VERSION} (gzip)"
107 # The writer method understands a few Symbols and will generate useful
108 # default authentication mechanisms.
110 options.key?(:authorization) ? options[:authorization] : :oauth_2
111 self.auto_refresh_token = options.fetch(:auto_refresh_token) { true }
112 self.key = options[:key]
113 self.user_ip = options[:user_ip]
114 self.retries = options.fetch(:retries) { 0 }
116 @discovery_documents = {}
117 @discovered_apis = {}
118 ca_file = options[:ca_file] || File.expand_path('../../cacerts.pem', __FILE__)
119 self.connection = Faraday.new do |faraday|
120 faraday.response :gzip
121 faraday.options.params_encoder = Faraday::FlatParamsEncoder
122 faraday.ssl.ca_file = ca_file
123 faraday.ssl.verify = true
125 faraday.adapter Faraday.default_adapter
131 # Returns the authorization mechanism used by the client.
133 # @return [#generate_authenticated_request] The authorization mechanism.
134 attr_reader :authorization
137 # Sets the authorization mechanism used by the client.
139 # @param [#generate_authenticated_request] new_authorization
140 # The new authorization mechanism.
141 def authorization=(new_authorization)
142 case new_authorization
143 when :oauth_1, :oauth
144 require 'signet/oauth_1/client'
145 # NOTE: Do not rely on this default value, as it may change
146 new_authorization = Signet::OAuth1::Client.new(
147 :temporary_credential_uri =>
148 'https://www.google.com/accounts/OAuthGetRequestToken',
149 :authorization_uri =>
150 'https://www.google.com/accounts/OAuthAuthorizeToken',
151 :token_credential_uri =>
152 'https://www.google.com/accounts/OAuthGetAccessToken',
153 :client_credential_key => 'anonymous',
154 :client_credential_secret => 'anonymous'
156 when :two_legged_oauth_1, :two_legged_oauth
157 require 'signet/oauth_1/client'
158 # NOTE: Do not rely on this default value, as it may change
159 new_authorization = Signet::OAuth1::Client.new(
160 :client_credential_key => nil,
161 :client_credential_secret => nil,
165 require 'signet/oauth_2/client'
166 # NOTE: Do not rely on this default value, as it may change
167 new_authorization = Signet::OAuth2::Client.new(
168 :authorization_uri =>
169 'https://accounts.google.com/o/oauth2/auth',
170 :token_credential_uri =>
171 'https://accounts.google.com/o/oauth2/token'
174 # No authorization mechanism
176 if !new_authorization.respond_to?(:generate_authenticated_request)
178 'Expected authorization mechanism to respond to ' +
179 '#generate_authenticated_request.'
182 @authorization = new_authorization
183 return @authorization
187 # Default Faraday/HTTP connection.
189 # @return [Faraday::Connection]
190 attr_accessor :connection
193 # The setting that controls whether or not the api client attempts to
194 # refresh authorization when a 401 is hit in #execute.
197 attr_accessor :auto_refresh_token
200 # The application's API key issued by the API console.
202 # @return [String] The API key.
206 # The IP address of the user this request is being performed on behalf of.
208 # @return [String] The user's IP address.
209 attr_accessor :user_ip
212 # The user agent used by the client.
215 # The user agent string used in the User-Agent header.
216 attr_accessor :user_agent
219 # The API hostname used by the client.
222 # The API hostname. Should almost always be 'www.googleapis.com'.
226 # The port number used by the client.
229 # The port number. Should almost always be 443.
233 # The base path used by the client for discovery.
236 # The base path. Should almost always be '/discovery/v1'.
237 attr_accessor :discovery_path
240 # Number of times to retry on recoverable errors
244 attr_accessor :retries
247 # Returns the URI for the directory document.
249 # @return [Addressable::URI] The URI of the directory document.
251 return resolve_uri(self.discovery_path + '/apis')
255 # Manually registers a URI as a discovery document for a specific version
258 # @param [String, Symbol] api The API name.
259 # @param [String] version The desired version of the API.
260 # @param [Addressable::URI] uri The URI of the discovery document.
261 def register_discovery_uri(api, version, uri)
263 version = version || 'v1'
264 @discovery_uris["#{api}:#{version}"] = uri
268 # Returns the URI for the discovery document.
270 # @param [String, Symbol] api The API name.
271 # @param [String] version The desired version of the API.
272 # @return [Addressable::URI] The URI of the discovery document.
273 def discovery_uri(api, version=nil)
275 version = version || 'v1'
276 return @discovery_uris["#{api}:#{version}"] ||= (
278 self.discovery_path + '/apis/{api}/{version}/rest',
286 # Manually registers a pre-loaded discovery document for a specific version
289 # @param [String, Symbol] api The API name.
290 # @param [String] version The desired version of the API.
291 # @param [String, StringIO] discovery_document
292 # The contents of the discovery document.
293 def register_discovery_document(api, version, discovery_document)
295 version = version || 'v1'
296 if discovery_document.kind_of?(StringIO)
297 discovery_document.rewind
298 discovery_document = discovery_document.string
299 elsif discovery_document.respond_to?(:to_str)
300 discovery_document = discovery_document.to_str
303 "Expected String or StringIO, got #{discovery_document.class}."
305 @discovery_documents["#{api}:#{version}"] =
306 MultiJson.load(discovery_document)
310 # Returns the parsed directory document.
312 # @return [Hash] The parsed JSON from the directory document.
313 def directory_document
314 return @directory_document ||= (begin
315 response = self.execute!(
316 :http_method => :get,
317 :uri => self.directory_uri,
318 :authenticated => false
325 # Returns the parsed discovery document.
327 # @param [String, Symbol] api The API name.
328 # @param [String] version The desired version of the API.
329 # @return [Hash] The parsed JSON from the discovery document.
330 def discovery_document(api, version=nil)
332 version = version || 'v1'
333 return @discovery_documents["#{api}:#{version}"] ||= (begin
334 response = self.execute!(
335 :http_method => :get,
336 :uri => self.discovery_uri(api, version),
337 :authenticated => false
344 # Returns all APIs published in the directory document.
346 # @return [Array] The list of available APIs.
348 @directory_apis ||= (begin
349 document_base = self.directory_uri
350 if self.directory_document && self.directory_document['items']
351 self.directory_document['items'].map do |discovery_document|
352 Google::APIClient::API.new(
364 # Returns the service object for a given service name and service version.
366 # @param [String, Symbol] api The API name.
367 # @param [String] version The desired version of the API.
369 # @return [Google::APIClient::API] The service object.
370 def discovered_api(api, version=nil)
371 if !api.kind_of?(String) && !api.kind_of?(Symbol)
373 "Expected String or Symbol, got #{api.class}."
376 version = version || 'v1'
377 return @discovered_apis["#{api}:#{version}"] ||= begin
378 document_base = self.discovery_uri(api, version)
379 discovery_document = self.discovery_document(api, version)
380 if document_base && discovery_document
381 Google::APIClient::API.new(
392 # Returns the method object for a given RPC name and service version.
394 # @param [String, Symbol] rpc_name The RPC name of the desired method.
395 # @param [String, Symbol] api The API the method is within.
396 # @param [String] version The desired version of the API.
398 # @return [Google::APIClient::Method] The method object.
399 def discovered_method(rpc_name, api, version=nil)
400 if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
402 "Expected String or Symbol, got #{rpc_name.class}."
404 rpc_name = rpc_name.to_s
406 version = version || 'v1'
407 service = self.discovered_api(api, version)
408 if service.to_h[rpc_name]
409 return service.to_h[rpc_name]
416 # Returns the service object with the highest version number.
418 # @note <em>Warning</em>: This method should be used with great care.
419 # As APIs are updated, minor differences between versions may cause
420 # incompatibilities. Requesting a specific version will avoid this issue.
422 # @param [String, Symbol] api The name of the service.
424 # @return [Google::APIClient::API] The service object.
425 def preferred_version(api)
426 if !api.kind_of?(String) && !api.kind_of?(Symbol)
428 "Expected String or Symbol, got #{api.class}."
431 return self.discovered_apis.detect do |a|
432 a.name == api && a.preferred == true
437 # Verifies an ID token against a server certificate. Used to ensure that
438 # an ID token supplied by an untrusted client-side mechanism is valid.
439 # Raises an error if the token is invalid or missing.
441 # @deprecated Use the google-id-token gem for verifying JWTs
446 if !self.authorization.respond_to?(:id_token)
447 raise ArgumentError, (
448 "Current authorization mechanism does not support ID tokens: " +
449 "#{self.authorization.class.to_s}"
451 elsif !self.authorization.id_token
452 raise ArgumentError, (
453 "Could not verify ID token, ID token missing. " +
454 "Scopes were: #{self.authorization.scope.inspect}"
457 check_cached_certs = lambda do
459 for key, cert in @certificates
461 self.authorization.decoded_id_token(cert.public_key)
463 rescue JWT::DecodeError, Signet::UnsafeOperationError
464 # Expected exception. Ignore, ID token has not been validated.
469 if check_cached_certs.call()
472 response = self.execute!(
473 :http_method => :get,
474 :uri => 'https://www.googleapis.com/oauth2/v1/certs',
475 :authenticated => false
477 @certificates.merge!(
478 Hash[MultiJson.load(response.body).map do |key, cert|
479 [key, OpenSSL::X509::Certificate.new(cert)]
482 if check_cached_certs.call()
485 raise InvalidIDTokenError,
486 "Could not verify ID token against any available certificate."
493 # Generates a request.
495 # @option options [Google::APIClient::Method] :api_method
496 # The method object or the RPC name of the method being executed.
497 # @option options [Hash, Array] :parameters
498 # The parameters to send to the method.
499 # @option options [Hash, Array] :headers The HTTP headers for the request.
500 # @option options [String] :body The body of the request.
501 # @option options [String] :version ("v1")
502 # The service version. Only used if `api_method` is a `String`.
503 # @option options [#generate_authenticated_request] :authorization
504 # The authorization mechanism for the response. Used only if
505 # `:authenticated` is `true`.
506 # @option options [TrueClass, FalseClass] :authenticated (true)
507 # `true` if the request must be signed or somehow
508 # authenticated, `false` otherwise.
510 # @return [Google::APIClient::Reference] The generated request.
513 # request = client.generate_request(
514 # :api_method => 'plus.activities.list',
516 # {'collection' => 'public', 'userId' => 'me'}
518 def generate_request(options={})
522 return Google::APIClient::Request.new(options)
526 # Executes a request, wrapping it in a Result object.
528 # @param [Google::APIClient::Request, Hash, Array] params
529 # Either a Google::APIClient::Request, a Hash, or an Array.
531 # If a Google::APIClient::Request, no other parameters are expected.
533 # If a Hash, the below parameters are handled. If an Array, the
534 # parameters are assumed to be in the below order:
536 # - (Google::APIClient::Method) api_method:
537 # The method object or the RPC name of the method being executed.
538 # - (Hash, Array) parameters:
539 # The parameters to send to the method.
540 # - (String) body: The body of the request.
541 # - (Hash, Array) headers: The HTTP headers for the request.
542 # - (Hash) options: A set of options for the request, of which:
543 # - (#generate_authenticated_request) :authorization (default: true) -
544 # The authorization mechanism for the response. Used only if
545 # `:authenticated` is `true`.
546 # - (TrueClass, FalseClass) :authenticated (default: true) -
547 # `true` if the request must be signed or somehow
548 # authenticated, `false` otherwise.
549 # - (TrueClass, FalseClass) :gzip (default: true) -
550 # `true` if gzip enabled, `false` otherwise.
551 # - (FixNum) :retries -
552 # # of times to retry on recoverable errors
554 # @return [Google::APIClient::Result] The result from the API, nil if batch.
557 # result = client.execute(batch_request)
560 # plus = client.discovered_api('plus')
561 # result = client.execute(
562 # :api_method => plus.activities.list,
563 # :parameters => {'collection' => 'public', 'userId' => 'me'}
566 # @see Google::APIClient#generate_request
567 def execute!(*params)
568 if params.first.kind_of?(Google::APIClient::Request)
569 request = params.shift
570 options = params.shift || {}
572 # This block of code allows us to accept multiple parameter passing
573 # styles, and maintaining some backwards compatibility.
575 # Note: I'm extremely tempted to deprecate this style of execute call.
576 if params.last.respond_to?(:to_hash) && params.size == 1
582 options[:api_method] = params.shift if params.size > 0
583 options[:parameters] = params.shift if params.size > 0
584 options[:body] = params.shift if params.size > 0
585 options[:headers] = params.shift if params.size > 0
586 options.update(params.shift) if params.size > 0
587 request = self.generate_request(options)
590 request.headers['User-Agent'] ||= '' + self.user_agent unless self.user_agent.nil?
591 request.headers['Accept-Encoding'] ||= 'gzip' unless options[:gzip] == false
592 request.headers['Content-Type'] ||= ''
593 request.parameters['key'] ||= self.key unless self.key.nil?
594 request.parameters['userIp'] ||= self.user_ip unless self.user_ip.nil?
596 connection = options[:connection] || self.connection
597 request.authorization = options[:authorization] || self.authorization unless options[:authenticated] == false
599 tries = 1 + (options[:retries] || self.retries)
601 Retriable.retriable :tries => tries,
602 :on => [TransmissionError],
603 :on_retry => client_error_handler(request.authorization),
604 :interval => lambda {|attempts| (2 ** attempts) + rand} do
605 result = request.send(connection, true)
610 when 301, 302, 303, 307
611 request = generate_request(request.to_hash.merge({
612 :uri => result.headers['location'],
615 raise RedirectError.new(result.headers['location'], result)
617 raise ClientError.new(result.error_message || "A client error has occurred", result)
619 raise ServerError.new(result.error_message || "A server error has occurred", result)
621 raise TransmissionError.new(result.error_message || "A transmission error has occurred", result)
627 # Same as Google::APIClient#execute!, but does not raise an exception for
630 # @see Google::APIClient#execute
633 return self.execute!(*params)
634 rescue TransmissionError => e
642 # Resolves a URI template against the client's configured base.
645 # @param [String, Addressable::URI, Addressable::Template] template
646 # The template to resolve.
647 # @param [Hash] mapping The mapping that corresponds to the template.
648 # @return [Addressable::URI] The expanded URI.
649 def resolve_uri(template, mapping={})
650 @base_uri ||= Addressable::URI.new(
655 template = if template.kind_of?(Addressable::Template)
657 elsif template.respond_to?(:to_str)
661 "Expected String, Addressable::URI, or Addressable::Template, " +
662 "got #{template.class}."
664 return Addressable::Template.new(@base_uri + template).expand(mapping)
669 # Returns on proc for special processing of retries as not all client errors
670 # are recoverable. Only 401s should be retried and only if the credentials
673 # @param [#fetch_access_token!] authorization
674 # OAuth 2 credentials
676 def client_error_handler(authorization)
677 can_refresh = authorization.respond_to?(:refresh_token) && auto_refresh_token
678 Proc.new do |exception, tries|
679 next unless exception.kind_of?(ClientError)
680 if exception.result.status == 401 && can_refresh && tries == 1
682 logger.debug("Attempting refresh of access token & retry of request")
683 authorization.fetch_access_token!
685 rescue Signet::AuthorizationError
696 require 'google/api_client/version'