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/utils'
19 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/railtie' if defined?(Rails)
38 # This class manages APIs communication.
40 include Google::APIClient::Logging
43 # Creates a new Google API client.
45 # @param [Hash] options The configuration parameters for the client.
46 # @option options [Symbol, #generate_authenticated_request] :authorization
48 # The authorization mechanism used by the client. The following
49 # mechanisms are supported out-of-the-box:
51 # <li><code>:two_legged_oauth_1</code></li>
52 # <li><code>:oauth_1</code></li>
53 # <li><code>:oauth_2</code></li>
55 # @option options [Boolean] :auto_refresh_token (true)
56 # The setting that controls whether or not the api client attempts to
57 # refresh authorization when a 401 is hit in #execute. If the token does
58 # not support it, this option is ignored.
59 # @option options [String] :application_name
60 # The name of the application using the client.
61 # @option options [String] :application_version
62 # The version number of the application using the client.
63 # @option options [String] :user_agent
64 # ("{app_name} google-api-ruby-client/{version} {os_name}/{os_version}")
65 # The user agent used by the client. Most developers will want to
66 # leave this value alone and use the `:application_name` option instead.
67 # @option options [String] :host ("www.googleapis.com")
68 # The API hostname used by the client. This rarely needs to be changed.
69 # @option options [String] :port (443)
70 # The port number used by the client. This rarely needs to be changed.
71 # @option options [String] :discovery_path ("/discovery/v1")
72 # The discovery base path. This rarely needs to be changed.
73 def initialize(options={})
74 logger.debug { "#{self.class} - Initializing client with options #{options}" }
76 # Normalize key to String to allow indifferent access.
77 options = options.inject({}) do |accu, (key, value)|
78 accu[key.to_sym] = value
81 # Almost all API usage will have a host of 'www.googleapis.com'.
82 self.host = options[:host] || 'www.googleapis.com'
83 self.port = options[:port] || 443
84 self.discovery_path = options[:discovery_path] || '/discovery/v1'
86 # Most developers will want to leave this value alone and use the
87 # application_name option.
88 if options[:application_name]
89 app_name = options[:application_name]
90 app_version = options[:application_version]
91 application_string = "#{app_name}/#{app_version || '0.0.0'}"
93 logger.warn { "#{self.class} - Please provide :application_name and :application_version when initializing the client" }
95 self.user_agent = options[:user_agent] || (
96 "#{application_string} " +
97 "google-api-ruby-client/#{Google::APIClient::VERSION::STRING} " +
100 # The writer method understands a few Symbols and will generate useful
101 # default authentication mechanisms.
103 options.key?(:authorization) ? options[:authorization] : :oauth_2
104 self.auto_refresh_token = options.fetch(:auto_refresh_token){ true }
105 self.key = options[:key]
106 self.user_ip = options[:user_ip]
108 @discovery_documents = {}
109 @discovered_apis = {}
115 # Returns the authorization mechanism used by the client.
117 # @return [#generate_authenticated_request] The authorization mechanism.
118 attr_reader :authorization
121 # Sets the authorization mechanism used by the client.
123 # @param [#generate_authenticated_request] new_authorization
124 # The new authorization mechanism.
125 def authorization=(new_authorization)
126 case new_authorization
127 when :oauth_1, :oauth
128 require 'signet/oauth_1/client'
129 # NOTE: Do not rely on this default value, as it may change
130 new_authorization = Signet::OAuth1::Client.new(
131 :temporary_credential_uri =>
132 'https://www.google.com/accounts/OAuthGetRequestToken',
133 :authorization_uri =>
134 'https://www.google.com/accounts/OAuthAuthorizeToken',
135 :token_credential_uri =>
136 'https://www.google.com/accounts/OAuthGetAccessToken',
137 :client_credential_key => 'anonymous',
138 :client_credential_secret => 'anonymous'
140 when :two_legged_oauth_1, :two_legged_oauth
141 require 'signet/oauth_1/client'
142 # NOTE: Do not rely on this default value, as it may change
143 new_authorization = Signet::OAuth1::Client.new(
144 :client_credential_key => nil,
145 :client_credential_secret => nil,
149 require 'signet/oauth_2/client'
150 # NOTE: Do not rely on this default value, as it may change
151 new_authorization = Signet::OAuth2::Client.new(
152 :authorization_uri =>
153 'https://accounts.google.com/o/oauth2/auth',
154 :token_credential_uri =>
155 'https://accounts.google.com/o/oauth2/token'
158 # No authorization mechanism
160 if !new_authorization.respond_to?(:generate_authenticated_request)
162 'Expected authorization mechanism to respond to ' +
163 '#generate_authenticated_request.'
166 @authorization = new_authorization
167 return @authorization
171 # The application's API key issued by the API console.
173 # @return [String] The API key.
177 # The setting that controls whether or not the api client attempts to
178 # refresh authorization when a 401 is hit in #execute.
181 attr_accessor :auto_refresh_token
184 # The IP address of the user this request is being performed on behalf of.
186 # @return [String] The user's IP address.
187 attr_accessor :user_ip
190 # The user agent used by the client.
193 # The user agent string used in the User-Agent header.
194 attr_accessor :user_agent
197 # The API hostname used by the client.
200 # The API hostname. Should almost always be 'www.googleapis.com'.
204 # The port number used by the client.
207 # The port number. Should almost always be 443.
211 # The base path used by the client for discovery.
214 # The base path. Should almost always be '/discovery/v1'.
215 attr_accessor :discovery_path
218 # Returns the URI for the directory document.
220 # @return [Addressable::URI] The URI of the directory document.
222 return resolve_uri(self.discovery_path + '/apis')
226 # Manually registers a URI as a discovery document for a specific version
229 # @param [String, Symbol] api The API name.
230 # @param [String] version The desired version of the API.
231 # @param [Addressable::URI] uri The URI of the discovery document.
232 def register_discovery_uri(api, version, uri)
234 version = version || 'v1'
235 @discovery_uris["#{api}:#{version}"] = uri
239 # Returns the URI for the discovery document.
241 # @param [String, Symbol] api The API name.
242 # @param [String] version The desired version of the API.
243 # @return [Addressable::URI] The URI of the discovery document.
244 def discovery_uri(api, version=nil)
246 version = version || 'v1'
247 return @discovery_uris["#{api}:#{version}"] ||= (
249 self.discovery_path + '/apis/{api}/{version}/rest',
257 # Manually registers a pre-loaded discovery document for a specific version
260 # @param [String, Symbol] api The API name.
261 # @param [String] version The desired version of the API.
262 # @param [String, StringIO] discovery_document
263 # The contents of the discovery document.
264 def register_discovery_document(api, version, discovery_document)
266 version = version || 'v1'
267 if discovery_document.kind_of?(StringIO)
268 discovery_document.rewind
269 discovery_document = discovery_document.string
270 elsif discovery_document.respond_to?(:to_str)
271 discovery_document = discovery_document.to_str
274 "Expected String or StringIO, got #{discovery_document.class}."
276 @discovery_documents["#{api}:#{version}"] =
277 MultiJson.load(discovery_document)
281 # Returns the parsed directory document.
283 # @return [Hash] The parsed JSON from the directory document.
284 def directory_document
285 return @directory_document ||= (begin
286 response = self.execute!(
287 :http_method => :get,
288 :uri => self.directory_uri,
289 :authenticated => false
296 # Returns the parsed discovery document.
298 # @param [String, Symbol] api The API name.
299 # @param [String] version The desired version of the API.
300 # @return [Hash] The parsed JSON from the discovery document.
301 def discovery_document(api, version=nil)
303 version = version || 'v1'
304 return @discovery_documents["#{api}:#{version}"] ||= (begin
305 response = self.execute!(
306 :http_method => :get,
307 :uri => self.discovery_uri(api, version),
308 :authenticated => false
315 # Returns all APIs published in the directory document.
317 # @return [Array] The list of available APIs.
319 @directory_apis ||= (begin
320 document_base = self.directory_uri
321 if self.directory_document && self.directory_document['items']
322 self.directory_document['items'].map do |discovery_document|
323 Google::APIClient::API.new(
335 # Returns the service object for a given service name and service version.
337 # @param [String, Symbol] api The API name.
338 # @param [String] version The desired version of the API.
340 # @return [Google::APIClient::API] The service object.
341 def discovered_api(api, version=nil)
342 if !api.kind_of?(String) && !api.kind_of?(Symbol)
344 "Expected String or Symbol, got #{api.class}."
347 version = version || 'v1'
348 return @discovered_apis["#{api}:#{version}"] ||= begin
349 document_base = self.discovery_uri(api, version)
350 discovery_document = self.discovery_document(api, version)
351 if document_base && discovery_document
352 Google::APIClient::API.new(
363 # Returns the method object for a given RPC name and service version.
365 # @param [String, Symbol] rpc_name The RPC name of the desired method.
366 # @param [String, Symbol] api The API the method is within.
367 # @param [String] version The desired version of the API.
369 # @return [Google::APIClient::Method] The method object.
370 def discovered_method(rpc_name, api, version=nil)
371 if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
373 "Expected String or Symbol, got #{rpc_name.class}."
375 rpc_name = rpc_name.to_s
377 version = version || 'v1'
378 service = self.discovered_api(api, version)
379 if service.to_h[rpc_name]
380 return service.to_h[rpc_name]
387 # Returns the service object with the highest version number.
389 # @note <em>Warning</em>: This method should be used with great care.
390 # As APIs are updated, minor differences between versions may cause
391 # incompatibilities. Requesting a specific version will avoid this issue.
393 # @param [String, Symbol] api The name of the service.
395 # @return [Google::APIClient::API] The service object.
396 def preferred_version(api)
397 if !api.kind_of?(String) && !api.kind_of?(Symbol)
399 "Expected String or Symbol, got #{api.class}."
402 return self.discovered_apis.detect do |a|
403 a.name == api && a.preferred == true
408 # Verifies an ID token against a server certificate. Used to ensure that
409 # an ID token supplied by an untrusted client-side mechanism is valid.
410 # Raises an error if the token is invalid or missing.
415 if !self.authorization.respond_to?(:id_token)
416 raise ArgumentError, (
417 "Current authorization mechanism does not support ID tokens: " +
418 "#{self.authorization.class.to_s}"
420 elsif !self.authorization.id_token
421 raise ArgumentError, (
422 "Could not verify ID token, ID token missing. " +
423 "Scopes were: #{self.authorization.scope.inspect}"
426 check_cached_certs = lambda do
428 for key, cert in @certificates
430 self.authorization.decoded_id_token(cert.public_key)
432 rescue JWT::DecodeError, Signet::UnsafeOperationError
433 # Expected exception. Ignore, ID token has not been validated.
438 if check_cached_certs.call()
441 response = self.execute!(
442 :http_method => :get,
443 :uri => 'https://www.googleapis.com/oauth2/v1/certs',
444 :authenticated => false
446 @certificates.merge!(
447 Hash[MultiJson.load(response.body).map do |key, cert|
448 [key, OpenSSL::X509::Certificate.new(cert)]
451 if check_cached_certs.call()
454 raise InvalidIDTokenError,
455 "Could not verify ID token against any available certificate."
462 # Generates a request.
464 # @option options [Google::APIClient::Method] :api_method
465 # The method object or the RPC name of the method being executed.
466 # @option options [Hash, Array] :parameters
467 # The parameters to send to the method.
468 # @option options [Hash, Array] :headers The HTTP headers for the request.
469 # @option options [String] :body The body of the request.
470 # @option options [String] :version ("v1")
471 # The service version. Only used if `api_method` is a `String`.
472 # @option options [#generate_authenticated_request] :authorization
473 # The authorization mechanism for the response. Used only if
474 # `:authenticated` is `true`.
475 # @option options [TrueClass, FalseClass] :authenticated (true)
476 # `true` if the request must be signed or somehow
477 # authenticated, `false` otherwise.
479 # @return [Google::APIClient::Reference] The generated request.
482 # request = client.generate_request(
483 # :api_method => 'plus.activities.list',
485 # {'collection' => 'public', 'userId' => 'me'}
487 def generate_request(options={})
491 return Google::APIClient::Request.new(options)
495 # Executes a request, wrapping it in a Result object.
497 # @param [Google::APIClient::Request, Hash, Array] params
498 # Either a Google::APIClient::Request, a Hash, or an Array.
500 # If a Google::APIClient::Request, no other parameters are expected.
502 # If a Hash, the below parameters are handled. If an Array, the
503 # parameters are assumed to be in the below order:
505 # - (Google::APIClient::Method) api_method:
506 # The method object or the RPC name of the method being executed.
507 # - (Hash, Array) parameters:
508 # The parameters to send to the method.
509 # - (String) body: The body of the request.
510 # - (Hash, Array) headers: The HTTP headers for the request.
511 # - (Hash) options: A set of options for the request, of which:
512 # - (#generate_authenticated_request) :authorization (default: true) -
513 # The authorization mechanism for the response. Used only if
514 # `:authenticated` is `true`.
515 # - (TrueClass, FalseClass) :authenticated (default: true) -
516 # `true` if the request must be signed or somehow
517 # authenticated, `false` otherwise.
519 # @return [Google::APIClient::Result] The result from the API, nil if batch.
522 # result = client.execute(batch_request)
525 # plus = client.discovered_api('plus')
526 # result = client.execute(
527 # :api_method => plus.activities.list,
528 # :parameters => {'collection' => 'public', 'userId' => 'me'}
531 # @see Google::APIClient#generate_request
533 if params.last.kind_of?(Google::APIClient::Request) &&
538 # This block of code allows us to accept multiple parameter passing
539 # styles, and maintaining some backwards compatibility.
541 # Note: I'm extremely tempted to deprecate this style of execute call.
542 if params.last.respond_to?(:to_hash) && params.size == 1
548 options[:api_method] = params.shift if params.size > 0
549 options[:parameters] = params.shift if params.size > 0
550 options[:body] = params.shift if params.size > 0
551 options[:headers] = params.shift if params.size > 0
552 options.update(params.shift) if params.size > 0
553 request = self.generate_request(options)
556 request.headers['User-Agent'] ||= '' + self.user_agent unless self.user_agent.nil?
557 request.parameters['key'] ||= self.key unless self.key.nil?
558 request.parameters['userIp'] ||= self.user_ip unless self.user_ip.nil?
560 connection = options[:connection] || Faraday.default_connection
561 request.authorization = options[:authorization] || self.authorization unless options[:authenticated] == false
563 result = request.send(connection)
564 if result.status == 401 && authorization.respond_to?(:refresh_token) && auto_refresh_token
566 logger.debug("Attempting refresh of access token & retry of request")
567 authorization.fetch_access_token!
568 result = request.send(connection)
569 rescue Signet::AuthorizationError
570 # Ignore since we want the original error
578 # Same as Google::APIClient#execute, but raises an exception if there was
581 # @see Google::APIClient#execute
582 def execute!(*params)
583 result = self.execute(*params)
585 error_message = result.error_message
586 case result.response.status
588 exception_type = ClientError
589 error_message ||= "A client error has occurred."
591 exception_type = ServerError
592 error_message ||= "A server error has occurred."
594 exception_type = TransmissionError
595 error_message ||= "A transmission error has occurred."
597 raise exception_type, error_message
605 # Resolves a URI template against the client's configured base.
608 # @param [String, Addressable::URI, Addressable::Template] template
609 # The template to resolve.
610 # @param [Hash] mapping The mapping that corresponds to the template.
611 # @return [Addressable::URI] The expanded URI.
612 def resolve_uri(template, mapping={})
613 @base_uri ||= Addressable::URI.new(
618 template = if template.kind_of?(Addressable::Template)
620 elsif template.respond_to?(:to_str)
624 "Expected String, Addressable::URI, or Addressable::Template, " +
625 "got #{template.class}."
627 return Addressable::Template.new(@base_uri + template).expand(mapping)
633 require 'google/api_client/version'