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/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" }
100 self.user_agent = options[:user_agent] || (
101 "#{application_string} " +
102 "google-api-ruby-client/#{Google::APIClient::VERSION::STRING} #{ENV::OS_VERSION} (gzip)"
104 # The writer method understands a few Symbols and will generate useful
105 # default authentication mechanisms.
107 options.key?(:authorization) ? options[:authorization] : :oauth_2
108 self.auto_refresh_token = options.fetch(:auto_refresh_token) { true }
109 self.key = options[:key]
110 self.user_ip = options[:user_ip]
112 @discovery_documents = {}
113 @discovered_apis = {}
114 ca_file = options[:ca_file] || File.expand_path('../../cacerts.pem', __FILE__)
115 self.connection = Faraday.new do |faraday|
116 faraday.response :gzip
117 faraday.options.params_encoder = Faraday::FlatParamsEncoder
118 faraday.ssl.ca_file = ca_file
119 faraday.ssl.verify = true
120 faraday.adapter Faraday.default_adapter
126 # Returns the authorization mechanism used by the client.
128 # @return [#generate_authenticated_request] The authorization mechanism.
129 attr_reader :authorization
132 # Sets the authorization mechanism used by the client.
134 # @param [#generate_authenticated_request] new_authorization
135 # The new authorization mechanism.
136 def authorization=(new_authorization)
137 case new_authorization
138 when :oauth_1, :oauth
139 require 'signet/oauth_1/client'
140 # NOTE: Do not rely on this default value, as it may change
141 new_authorization = Signet::OAuth1::Client.new(
142 :temporary_credential_uri =>
143 'https://www.google.com/accounts/OAuthGetRequestToken',
144 :authorization_uri =>
145 'https://www.google.com/accounts/OAuthAuthorizeToken',
146 :token_credential_uri =>
147 'https://www.google.com/accounts/OAuthGetAccessToken',
148 :client_credential_key => 'anonymous',
149 :client_credential_secret => 'anonymous'
151 when :two_legged_oauth_1, :two_legged_oauth
152 require 'signet/oauth_1/client'
153 # NOTE: Do not rely on this default value, as it may change
154 new_authorization = Signet::OAuth1::Client.new(
155 :client_credential_key => nil,
156 :client_credential_secret => nil,
160 require 'signet/oauth_2/client'
161 # NOTE: Do not rely on this default value, as it may change
162 new_authorization = Signet::OAuth2::Client.new(
163 :authorization_uri =>
164 'https://accounts.google.com/o/oauth2/auth',
165 :token_credential_uri =>
166 'https://accounts.google.com/o/oauth2/token'
169 # No authorization mechanism
171 if !new_authorization.respond_to?(:generate_authenticated_request)
173 'Expected authorization mechanism to respond to ' +
174 '#generate_authenticated_request.'
177 @authorization = new_authorization
178 return @authorization
182 # Default Faraday/HTTP connection.
184 # @return [Faraday::Connection]
185 attr_accessor :connection
188 # The setting that controls whether or not the api client attempts to
189 # refresh authorization when a 401 is hit in #execute.
192 attr_accessor :auto_refresh_token
195 # The application's API key issued by the API console.
197 # @return [String] The API key.
201 # The IP address of the user this request is being performed on behalf of.
203 # @return [String] The user's IP address.
204 attr_accessor :user_ip
207 # The user agent used by the client.
210 # The user agent string used in the User-Agent header.
211 attr_accessor :user_agent
214 # The API hostname used by the client.
217 # The API hostname. Should almost always be 'www.googleapis.com'.
221 # The port number used by the client.
224 # The port number. Should almost always be 443.
228 # The base path used by the client for discovery.
231 # The base path. Should almost always be '/discovery/v1'.
232 attr_accessor :discovery_path
235 # Returns the URI for the directory document.
237 # @return [Addressable::URI] The URI of the directory document.
239 return resolve_uri(self.discovery_path + '/apis')
243 # Manually registers a URI as a discovery document for a specific version
246 # @param [String, Symbol] api The API name.
247 # @param [String] version The desired version of the API.
248 # @param [Addressable::URI] uri The URI of the discovery document.
249 def register_discovery_uri(api, version, uri)
251 version = version || 'v1'
252 @discovery_uris["#{api}:#{version}"] = uri
256 # Returns the URI for the discovery document.
258 # @param [String, Symbol] api The API name.
259 # @param [String] version The desired version of the API.
260 # @return [Addressable::URI] The URI of the discovery document.
261 def discovery_uri(api, version=nil)
263 version = version || 'v1'
264 return @discovery_uris["#{api}:#{version}"] ||= (
266 self.discovery_path + '/apis/{api}/{version}/rest',
274 # Manually registers a pre-loaded discovery document for a specific version
277 # @param [String, Symbol] api The API name.
278 # @param [String] version The desired version of the API.
279 # @param [String, StringIO] discovery_document
280 # The contents of the discovery document.
281 def register_discovery_document(api, version, discovery_document)
283 version = version || 'v1'
284 if discovery_document.kind_of?(StringIO)
285 discovery_document.rewind
286 discovery_document = discovery_document.string
287 elsif discovery_document.respond_to?(:to_str)
288 discovery_document = discovery_document.to_str
291 "Expected String or StringIO, got #{discovery_document.class}."
293 @discovery_documents["#{api}:#{version}"] =
294 MultiJson.load(discovery_document)
298 # Returns the parsed directory document.
300 # @return [Hash] The parsed JSON from the directory document.
301 def directory_document
302 return @directory_document ||= (begin
303 response = self.execute!(
304 :http_method => :get,
305 :uri => self.directory_uri,
306 :authenticated => false
313 # Returns the parsed discovery document.
315 # @param [String, Symbol] api The API name.
316 # @param [String] version The desired version of the API.
317 # @return [Hash] The parsed JSON from the discovery document.
318 def discovery_document(api, version=nil)
320 version = version || 'v1'
321 return @discovery_documents["#{api}:#{version}"] ||= (begin
322 response = self.execute!(
323 :http_method => :get,
324 :uri => self.discovery_uri(api, version),
325 :authenticated => false
332 # Returns all APIs published in the directory document.
334 # @return [Array] The list of available APIs.
336 @directory_apis ||= (begin
337 document_base = self.directory_uri
338 if self.directory_document && self.directory_document['items']
339 self.directory_document['items'].map do |discovery_document|
340 Google::APIClient::API.new(
352 # Returns the service object for a given service name and service version.
354 # @param [String, Symbol] api The API name.
355 # @param [String] version The desired version of the API.
357 # @return [Google::APIClient::API] The service object.
358 def discovered_api(api, version=nil)
359 if !api.kind_of?(String) && !api.kind_of?(Symbol)
361 "Expected String or Symbol, got #{api.class}."
364 version = version || 'v1'
365 return @discovered_apis["#{api}:#{version}"] ||= begin
366 document_base = self.discovery_uri(api, version)
367 discovery_document = self.discovery_document(api, version)
368 if document_base && discovery_document
369 Google::APIClient::API.new(
380 # Returns the method object for a given RPC name and service version.
382 # @param [String, Symbol] rpc_name The RPC name of the desired method.
383 # @param [String, Symbol] api The API the method is within.
384 # @param [String] version The desired version of the API.
386 # @return [Google::APIClient::Method] The method object.
387 def discovered_method(rpc_name, api, version=nil)
388 if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
390 "Expected String or Symbol, got #{rpc_name.class}."
392 rpc_name = rpc_name.to_s
394 version = version || 'v1'
395 service = self.discovered_api(api, version)
396 if service.to_h[rpc_name]
397 return service.to_h[rpc_name]
404 # Returns the service object with the highest version number.
406 # @note <em>Warning</em>: This method should be used with great care.
407 # As APIs are updated, minor differences between versions may cause
408 # incompatibilities. Requesting a specific version will avoid this issue.
410 # @param [String, Symbol] api The name of the service.
412 # @return [Google::APIClient::API] The service object.
413 def preferred_version(api)
414 if !api.kind_of?(String) && !api.kind_of?(Symbol)
416 "Expected String or Symbol, got #{api.class}."
419 return self.discovered_apis.detect do |a|
420 a.name == api && a.preferred == true
425 # Verifies an ID token against a server certificate. Used to ensure that
426 # an ID token supplied by an untrusted client-side mechanism is valid.
427 # Raises an error if the token is invalid or missing.
432 if !self.authorization.respond_to?(:id_token)
433 raise ArgumentError, (
434 "Current authorization mechanism does not support ID tokens: " +
435 "#{self.authorization.class.to_s}"
437 elsif !self.authorization.id_token
438 raise ArgumentError, (
439 "Could not verify ID token, ID token missing. " +
440 "Scopes were: #{self.authorization.scope.inspect}"
443 check_cached_certs = lambda do
445 for key, cert in @certificates
447 self.authorization.decoded_id_token(cert.public_key)
449 rescue JWT::DecodeError, Signet::UnsafeOperationError
450 # Expected exception. Ignore, ID token has not been validated.
455 if check_cached_certs.call()
458 response = self.execute!(
459 :http_method => :get,
460 :uri => 'https://www.googleapis.com/oauth2/v1/certs',
461 :authenticated => false
463 @certificates.merge!(
464 Hash[MultiJson.load(response.body).map do |key, cert|
465 [key, OpenSSL::X509::Certificate.new(cert)]
468 if check_cached_certs.call()
471 raise InvalidIDTokenError,
472 "Could not verify ID token against any available certificate."
479 # Generates a request.
481 # @option options [Google::APIClient::Method] :api_method
482 # The method object or the RPC name of the method being executed.
483 # @option options [Hash, Array] :parameters
484 # The parameters to send to the method.
485 # @option options [Hash, Array] :headers The HTTP headers for the request.
486 # @option options [String] :body The body of the request.
487 # @option options [String] :version ("v1")
488 # The service version. Only used if `api_method` is a `String`.
489 # @option options [#generate_authenticated_request] :authorization
490 # The authorization mechanism for the response. Used only if
491 # `:authenticated` is `true`.
492 # @option options [TrueClass, FalseClass] :authenticated (true)
493 # `true` if the request must be signed or somehow
494 # authenticated, `false` otherwise.
496 # @return [Google::APIClient::Reference] The generated request.
499 # request = client.generate_request(
500 # :api_method => 'plus.activities.list',
502 # {'collection' => 'public', 'userId' => 'me'}
504 def generate_request(options={})
508 return Google::APIClient::Request.new(options)
512 # Executes a request, wrapping it in a Result object.
514 # @param [Google::APIClient::Request, Hash, Array] params
515 # Either a Google::APIClient::Request, a Hash, or an Array.
517 # If a Google::APIClient::Request, no other parameters are expected.
519 # If a Hash, the below parameters are handled. If an Array, the
520 # parameters are assumed to be in the below order:
522 # - (Google::APIClient::Method) api_method:
523 # The method object or the RPC name of the method being executed.
524 # - (Hash, Array) parameters:
525 # The parameters to send to the method.
526 # - (String) body: The body of the request.
527 # - (Hash, Array) headers: The HTTP headers for the request.
528 # - (Hash) options: A set of options for the request, of which:
529 # - (#generate_authenticated_request) :authorization (default: true) -
530 # The authorization mechanism for the response. Used only if
531 # `:authenticated` is `true`.
532 # - (TrueClass, FalseClass) :authenticated (default: true) -
533 # `true` if the request must be signed or somehow
534 # authenticated, `false` otherwise.
535 # - (TrueClass, FalseClass) :gzip (default: true) -
536 # `true` if gzip enabled, `false` otherwise.
538 # @return [Google::APIClient::Result] The result from the API, nil if batch.
541 # result = client.execute(batch_request)
544 # plus = client.discovered_api('plus')
545 # result = client.execute(
546 # :api_method => plus.activities.list,
547 # :parameters => {'collection' => 'public', 'userId' => 'me'}
550 # @see Google::APIClient#generate_request
552 if params.first.kind_of?(Google::APIClient::Request)
553 request = params.shift
554 options = params.shift || {}
556 # This block of code allows us to accept multiple parameter passing
557 # styles, and maintaining some backwards compatibility.
559 # Note: I'm extremely tempted to deprecate this style of execute call.
560 if params.last.respond_to?(:to_hash) && params.size == 1
566 options[:api_method] = params.shift if params.size > 0
567 options[:parameters] = params.shift if params.size > 0
568 options[:body] = params.shift if params.size > 0
569 options[:headers] = params.shift if params.size > 0
570 options.update(params.shift) if params.size > 0
571 request = self.generate_request(options)
574 request.headers['User-Agent'] ||= '' + self.user_agent unless self.user_agent.nil?
575 request.headers['Accept-Encoding'] ||= 'gzip' unless options[:gzip] == false
576 request.parameters['key'] ||= self.key unless self.key.nil?
577 request.parameters['userIp'] ||= self.user_ip unless self.user_ip.nil?
579 connection = options[:connection] || self.connection
580 request.authorization = options[:authorization] || self.authorization unless options[:authenticated] == false
582 result = request.send(connection)
583 if result.status == 401 && request.authorization.respond_to?(:refresh_token) && auto_refresh_token
585 logger.debug("Attempting refresh of access token & retry of request")
586 request.authorization.fetch_access_token!
587 result = request.send(connection, true)
588 rescue Signet::AuthorizationError
589 # Ignore since we want the original error
597 # Same as Google::APIClient#execute, but raises an exception if there was
600 # @see Google::APIClient#execute
601 def execute!(*params)
602 result = self.execute(*params)
604 error_message = result.error_message
605 case result.response.status
607 exception_type = ClientError
608 error_message ||= "A client error has occurred."
610 exception_type = ServerError
611 error_message ||= "A server error has occurred."
613 exception_type = TransmissionError
614 error_message ||= "A transmission error has occurred."
616 raise exception_type, error_message
624 # Resolves a URI template against the client's configured base.
627 # @param [String, Addressable::URI, Addressable::Template] template
628 # The template to resolve.
629 # @param [Hash] mapping The mapping that corresponds to the template.
630 # @return [Addressable::URI] The expanded URI.
631 def resolve_uri(template, mapping={})
632 @base_uri ||= Addressable::URI.new(
637 template = if template.kind_of?(Addressable::Template)
639 elsif template.respond_to?(:to_str)
643 "Expected String, Addressable::URI, or Addressable::Template, " +
644 "got #{template.class}."
646 return Addressable::Template.new(@base_uri + template).expand(mapping)
652 require 'google/api_client/version'