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'
21 require 'google/api_client/version'
22 require 'google/api_client/logging'
23 require 'google/api_client/errors'
24 require 'google/api_client/environment'
25 require 'google/api_client/discovery'
26 require 'google/api_client/request'
27 require 'google/api_client/reference'
28 require 'google/api_client/result'
29 require 'google/api_client/media'
30 require 'google/api_client/service_account'
31 require 'google/api_client/batch'
32 require 'google/api_client/gzip'
33 require 'google/api_client/client_secrets'
34 require 'google/api_client/railtie' if defined?(Rails::Railtie)
39 # This class manages APIs communication.
41 include Google::APIClient::Logging
44 # Creates a new Google API client.
46 # @param [Hash] options The configuration parameters for the client.
47 # @option options [Symbol, #generate_authenticated_request] :authorization
49 # The authorization mechanism used by the client. The following
50 # mechanisms are supported out-of-the-box:
52 # <li><code>:two_legged_oauth_1</code></li>
53 # <li><code>:oauth_1</code></li>
54 # <li><code>:oauth_2</code></li>
56 # @option options [Boolean] :auto_refresh_token (true)
57 # The setting that controls whether or not the api client attempts to
58 # refresh authorization when a 401 is hit in #execute. If the token does
59 # not support it, this option is ignored.
60 # @option options [String] :application_name
61 # The name of the application using the client.
62 # @option options [String] :application_version
63 # The version number of the application using the client.
64 # @option options [String] :user_agent
65 # ("{app_name} google-api-ruby-client/{version} {os_name}/{os_version}")
66 # The user agent used by the client. Most developers will want to
67 # leave this value alone and use the `:application_name` option instead.
68 # @option options [String] :host ("www.googleapis.com")
69 # The API hostname used by the client. This rarely needs to be changed.
70 # @option options [String] :port (443)
71 # The port number used by the client. This rarely needs to be changed.
72 # @option options [String] :discovery_path ("/discovery/v1")
73 # The discovery base path. This rarely needs to be changed.
74 # @option options [String] :ca_file
75 # Optional set of root certificates to use when validating SSL connections.
76 # By default, a bundled set of trusted roots will be used.
77 def initialize(options={})
78 logger.debug { "#{self.class} - Initializing client with options #{options}" }
80 # Normalize key to String to allow indifferent access.
81 options = options.inject({}) do |accu, (key, value)|
82 accu[key.to_sym] = value
85 # Almost all API usage will have a host of 'www.googleapis.com'.
86 self.host = options[:host] || 'www.googleapis.com'
87 self.port = options[:port] || 443
88 self.discovery_path = options[:discovery_path] || '/discovery/v1'
90 # Most developers will want to leave this value alone and use the
91 # application_name option.
92 if options[:application_name]
93 app_name = options[:application_name]
94 app_version = options[:application_version]
95 application_string = "#{app_name}/#{app_version || '0.0.0'}"
97 logger.warn { "#{self.class} - Please provide :application_name and :application_version when initializing the client" }
99 self.user_agent = options[:user_agent] || (
100 "#{application_string} " +
101 "google-api-ruby-client/#{Google::APIClient::VERSION::STRING} #{ENV::OS_VERSION} (gzip)"
103 # The writer method understands a few Symbols and will generate useful
104 # default authentication mechanisms.
106 options.key?(:authorization) ? options[:authorization] : :oauth_2
107 self.auto_refresh_token = options.fetch(:auto_refresh_token) { true }
108 self.key = options[:key]
109 self.user_ip = options[:user_ip]
111 @discovery_documents = {}
112 @discovered_apis = {}
113 ca_file = options[:ca_file] || File.expand_path('../../cacerts.pem', __FILE__)
114 self.connection = Faraday.new do |faraday|
115 faraday.response :gzip
116 faraday.options.params_encoder = Faraday::FlatParamsEncoder
117 faraday.ssl.ca_file = ca_file
118 faraday.ssl.verify = true
119 faraday.adapter Faraday.default_adapter
125 # Returns the authorization mechanism used by the client.
127 # @return [#generate_authenticated_request] The authorization mechanism.
128 attr_reader :authorization
131 # Sets the authorization mechanism used by the client.
133 # @param [#generate_authenticated_request] new_authorization
134 # The new authorization mechanism.
135 def authorization=(new_authorization)
136 case new_authorization
137 when :oauth_1, :oauth
138 require 'signet/oauth_1/client'
139 # NOTE: Do not rely on this default value, as it may change
140 new_authorization = Signet::OAuth1::Client.new(
141 :temporary_credential_uri =>
142 'https://www.google.com/accounts/OAuthGetRequestToken',
143 :authorization_uri =>
144 'https://www.google.com/accounts/OAuthAuthorizeToken',
145 :token_credential_uri =>
146 'https://www.google.com/accounts/OAuthGetAccessToken',
147 :client_credential_key => 'anonymous',
148 :client_credential_secret => 'anonymous'
150 when :two_legged_oauth_1, :two_legged_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 :client_credential_key => nil,
155 :client_credential_secret => nil,
159 require 'signet/oauth_2/client'
160 # NOTE: Do not rely on this default value, as it may change
161 new_authorization = Signet::OAuth2::Client.new(
162 :authorization_uri =>
163 'https://accounts.google.com/o/oauth2/auth',
164 :token_credential_uri =>
165 'https://accounts.google.com/o/oauth2/token'
168 # No authorization mechanism
170 if !new_authorization.respond_to?(:generate_authenticated_request)
172 'Expected authorization mechanism to respond to ' +
173 '#generate_authenticated_request.'
176 @authorization = new_authorization
177 return @authorization
181 # Default Faraday/HTTP connection.
183 # @return [Faraday::Connection]
184 attr_accessor :connection
187 # The setting that controls whether or not the api client attempts to
188 # refresh authorization when a 401 is hit in #execute.
191 attr_accessor :auto_refresh_token
194 # The application's API key issued by the API console.
196 # @return [String] The API key.
200 # The IP address of the user this request is being performed on behalf of.
202 # @return [String] The user's IP address.
203 attr_accessor :user_ip
206 # The user agent used by the client.
209 # The user agent string used in the User-Agent header.
210 attr_accessor :user_agent
213 # The API hostname used by the client.
216 # The API hostname. Should almost always be 'www.googleapis.com'.
220 # The port number used by the client.
223 # The port number. Should almost always be 443.
227 # The base path used by the client for discovery.
230 # The base path. Should almost always be '/discovery/v1'.
231 attr_accessor :discovery_path
234 # Returns the URI for the directory document.
236 # @return [Addressable::URI] The URI of the directory document.
238 return resolve_uri(self.discovery_path + '/apis')
242 # Manually registers a URI as a discovery document for a specific version
245 # @param [String, Symbol] api The API name.
246 # @param [String] version The desired version of the API.
247 # @param [Addressable::URI] uri The URI of the discovery document.
248 def register_discovery_uri(api, version, uri)
250 version = version || 'v1'
251 @discovery_uris["#{api}:#{version}"] = uri
255 # Returns the URI for the discovery document.
257 # @param [String, Symbol] api The API name.
258 # @param [String] version The desired version of the API.
259 # @return [Addressable::URI] The URI of the discovery document.
260 def discovery_uri(api, version=nil)
262 version = version || 'v1'
263 return @discovery_uris["#{api}:#{version}"] ||= (
265 self.discovery_path + '/apis/{api}/{version}/rest',
273 # Manually registers a pre-loaded discovery document for a specific version
276 # @param [String, Symbol] api The API name.
277 # @param [String] version The desired version of the API.
278 # @param [String, StringIO] discovery_document
279 # The contents of the discovery document.
280 def register_discovery_document(api, version, discovery_document)
282 version = version || 'v1'
283 if discovery_document.kind_of?(StringIO)
284 discovery_document.rewind
285 discovery_document = discovery_document.string
286 elsif discovery_document.respond_to?(:to_str)
287 discovery_document = discovery_document.to_str
290 "Expected String or StringIO, got #{discovery_document.class}."
292 @discovery_documents["#{api}:#{version}"] =
293 MultiJson.load(discovery_document)
297 # Returns the parsed directory document.
299 # @return [Hash] The parsed JSON from the directory document.
300 def directory_document
301 return @directory_document ||= (begin
302 response = self.execute!(
303 :http_method => :get,
304 :uri => self.directory_uri,
305 :authenticated => false
312 # Returns the parsed discovery document.
314 # @param [String, Symbol] api The API name.
315 # @param [String] version The desired version of the API.
316 # @return [Hash] The parsed JSON from the discovery document.
317 def discovery_document(api, version=nil)
319 version = version || 'v1'
320 return @discovery_documents["#{api}:#{version}"] ||= (begin
321 response = self.execute!(
322 :http_method => :get,
323 :uri => self.discovery_uri(api, version),
324 :authenticated => false
331 # Returns all APIs published in the directory document.
333 # @return [Array] The list of available APIs.
335 @directory_apis ||= (begin
336 document_base = self.directory_uri
337 if self.directory_document && self.directory_document['items']
338 self.directory_document['items'].map do |discovery_document|
339 Google::APIClient::API.new(
351 # Returns the service object for a given service name and service version.
353 # @param [String, Symbol] api The API name.
354 # @param [String] version The desired version of the API.
356 # @return [Google::APIClient::API] The service object.
357 def discovered_api(api, version=nil)
358 if !api.kind_of?(String) && !api.kind_of?(Symbol)
360 "Expected String or Symbol, got #{api.class}."
363 version = version || 'v1'
364 return @discovered_apis["#{api}:#{version}"] ||= begin
365 document_base = self.discovery_uri(api, version)
366 discovery_document = self.discovery_document(api, version)
367 if document_base && discovery_document
368 Google::APIClient::API.new(
379 # Returns the method object for a given RPC name and service version.
381 # @param [String, Symbol] rpc_name The RPC name of the desired method.
382 # @param [String, Symbol] api The API the method is within.
383 # @param [String] version The desired version of the API.
385 # @return [Google::APIClient::Method] The method object.
386 def discovered_method(rpc_name, api, version=nil)
387 if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
389 "Expected String or Symbol, got #{rpc_name.class}."
391 rpc_name = rpc_name.to_s
393 version = version || 'v1'
394 service = self.discovered_api(api, version)
395 if service.to_h[rpc_name]
396 return service.to_h[rpc_name]
403 # Returns the service object with the highest version number.
405 # @note <em>Warning</em>: This method should be used with great care.
406 # As APIs are updated, minor differences between versions may cause
407 # incompatibilities. Requesting a specific version will avoid this issue.
409 # @param [String, Symbol] api The name of the service.
411 # @return [Google::APIClient::API] The service object.
412 def preferred_version(api)
413 if !api.kind_of?(String) && !api.kind_of?(Symbol)
415 "Expected String or Symbol, got #{api.class}."
418 return self.discovered_apis.detect do |a|
419 a.name == api && a.preferred == true
424 # Verifies an ID token against a server certificate. Used to ensure that
425 # an ID token supplied by an untrusted client-side mechanism is valid.
426 # Raises an error if the token is invalid or missing.
431 if !self.authorization.respond_to?(:id_token)
432 raise ArgumentError, (
433 "Current authorization mechanism does not support ID tokens: " +
434 "#{self.authorization.class.to_s}"
436 elsif !self.authorization.id_token
437 raise ArgumentError, (
438 "Could not verify ID token, ID token missing. " +
439 "Scopes were: #{self.authorization.scope.inspect}"
442 check_cached_certs = lambda do
444 for key, cert in @certificates
446 self.authorization.decoded_id_token(cert.public_key)
448 rescue JWT::DecodeError, Signet::UnsafeOperationError
449 # Expected exception. Ignore, ID token has not been validated.
454 if check_cached_certs.call()
457 response = self.execute!(
458 :http_method => :get,
459 :uri => 'https://www.googleapis.com/oauth2/v1/certs',
460 :authenticated => false
462 @certificates.merge!(
463 Hash[MultiJson.load(response.body).map do |key, cert|
464 [key, OpenSSL::X509::Certificate.new(cert)]
467 if check_cached_certs.call()
470 raise InvalidIDTokenError,
471 "Could not verify ID token against any available certificate."
478 # Generates a request.
480 # @option options [Google::APIClient::Method] :api_method
481 # The method object or the RPC name of the method being executed.
482 # @option options [Hash, Array] :parameters
483 # The parameters to send to the method.
484 # @option options [Hash, Array] :headers The HTTP headers for the request.
485 # @option options [String] :body The body of the request.
486 # @option options [String] :version ("v1")
487 # The service version. Only used if `api_method` is a `String`.
488 # @option options [#generate_authenticated_request] :authorization
489 # The authorization mechanism for the response. Used only if
490 # `:authenticated` is `true`.
491 # @option options [TrueClass, FalseClass] :authenticated (true)
492 # `true` if the request must be signed or somehow
493 # authenticated, `false` otherwise.
495 # @return [Google::APIClient::Reference] The generated request.
498 # request = client.generate_request(
499 # :api_method => 'plus.activities.list',
501 # {'collection' => 'public', 'userId' => 'me'}
503 def generate_request(options={})
507 return Google::APIClient::Request.new(options)
511 # Executes a request, wrapping it in a Result object.
513 # @param [Google::APIClient::Request, Hash, Array] params
514 # Either a Google::APIClient::Request, a Hash, or an Array.
516 # If a Google::APIClient::Request, no other parameters are expected.
518 # If a Hash, the below parameters are handled. If an Array, the
519 # parameters are assumed to be in the below order:
521 # - (Google::APIClient::Method) api_method:
522 # The method object or the RPC name of the method being executed.
523 # - (Hash, Array) parameters:
524 # The parameters to send to the method.
525 # - (String) body: The body of the request.
526 # - (Hash, Array) headers: The HTTP headers for the request.
527 # - (Hash) options: A set of options for the request, of which:
528 # - (#generate_authenticated_request) :authorization (default: true) -
529 # The authorization mechanism for the response. Used only if
530 # `:authenticated` is `true`.
531 # - (TrueClass, FalseClass) :authenticated (default: true) -
532 # `true` if the request must be signed or somehow
533 # authenticated, `false` otherwise.
534 # - (TrueClass, FalseClass) :gzip (default: true) -
535 # `true` if gzip enabled, `false` otherwise.
537 # @return [Google::APIClient::Result] The result from the API, nil if batch.
540 # result = client.execute(batch_request)
543 # plus = client.discovered_api('plus')
544 # result = client.execute(
545 # :api_method => plus.activities.list,
546 # :parameters => {'collection' => 'public', 'userId' => 'me'}
549 # @see Google::APIClient#generate_request
551 if params.first.kind_of?(Google::APIClient::Request)
552 request = params.shift
553 options = params.shift || {}
555 # This block of code allows us to accept multiple parameter passing
556 # styles, and maintaining some backwards compatibility.
558 # Note: I'm extremely tempted to deprecate this style of execute call.
559 if params.last.respond_to?(:to_hash) && params.size == 1
565 options[:api_method] = params.shift if params.size > 0
566 options[:parameters] = params.shift if params.size > 0
567 options[:body] = params.shift if params.size > 0
568 options[:headers] = params.shift if params.size > 0
569 options.update(params.shift) if params.size > 0
570 request = self.generate_request(options)
573 request.headers['User-Agent'] ||= '' + self.user_agent unless self.user_agent.nil?
574 request.headers['Accept-Encoding'] ||= 'gzip' unless options[:gzip] == false
575 request.parameters['key'] ||= self.key unless self.key.nil?
576 request.parameters['userIp'] ||= self.user_ip unless self.user_ip.nil?
578 connection = options[:connection] || self.connection
579 request.authorization = options[:authorization] || self.authorization unless options[:authenticated] == false
581 result = request.send(connection)
582 if result.status == 401 && request.authorization.respond_to?(:refresh_token) && auto_refresh_token
584 logger.debug("Attempting refresh of access token & retry of request")
585 request.authorization.fetch_access_token!
586 result = request.send(connection, true)
587 rescue Signet::AuthorizationError
588 # Ignore since we want the original error
596 # Same as Google::APIClient#execute, but raises an exception if there was
599 # @see Google::APIClient#execute
600 def execute!(*params)
601 result = self.execute(*params)
603 error_message = result.error_message
604 case result.response.status
606 exception_type = ClientError
607 error_message ||= "A client error has occurred."
609 exception_type = ServerError
610 error_message ||= "A server error has occurred."
612 exception_type = TransmissionError
613 error_message ||= "A transmission error has occurred."
615 raise exception_type, error_message
623 # Resolves a URI template against the client's configured base.
626 # @param [String, Addressable::URI, Addressable::Template] template
627 # The template to resolve.
628 # @param [Hash] mapping The mapping that corresponds to the template.
629 # @return [Addressable::URI] The expanded URI.
630 def resolve_uri(template, mapping={})
631 @base_uri ||= Addressable::URI.new(
636 template = if template.kind_of?(Addressable::Template)
638 elsif template.respond_to?(:to_str)
642 "Expected String, Addressable::URI, or Addressable::Template, " +
643 "got #{template.class}."
645 return Addressable::Template.new(@base_uri + template).expand(mapping)
651 require 'google/api_client/version'