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::Railtie)
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 # @option options [String] :ca_file
74 # Optional set of root certificates to use when validating SSL connections.
75 # By default, a bundled set of trusted roots will be used.
76 def initialize(options={})
77 logger.debug { "#{self.class} - Initializing client with options #{options}" }
79 # Normalize key to String to allow indifferent access.
80 options = options.inject({}) do |accu, (key, value)|
81 accu[key.to_sym] = value
84 # Almost all API usage will have a host of 'www.googleapis.com'.
85 self.host = options[:host] || 'www.googleapis.com'
86 self.port = options[:port] || 443
87 self.discovery_path = options[:discovery_path] || '/discovery/v1'
89 # Most developers will want to leave this value alone and use the
90 # application_name option.
91 if options[:application_name]
92 app_name = options[:application_name]
93 app_version = options[:application_version]
94 application_string = "#{app_name}/#{app_version || '0.0.0'}"
96 logger.warn { "#{self.class} - Please provide :application_name and :application_version when initializing the client" }
98 self.user_agent = options[:user_agent] || (
99 "#{application_string} " +
100 "google-api-ruby-client/#{Google::APIClient::VERSION::STRING} " +
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.options.params_encoder = Faraday::FlatParamsEncoder
116 faraday.ssl.ca_file = ca_file
117 faraday.ssl.verify = true
118 faraday.adapter Faraday.default_adapter
124 # Returns the authorization mechanism used by the client.
126 # @return [#generate_authenticated_request] The authorization mechanism.
127 attr_reader :authorization
130 # Sets the authorization mechanism used by the client.
132 # @param [#generate_authenticated_request] new_authorization
133 # The new authorization mechanism.
134 def authorization=(new_authorization)
135 case new_authorization
136 when :oauth_1, :oauth
137 require 'signet/oauth_1/client'
138 # NOTE: Do not rely on this default value, as it may change
139 new_authorization = Signet::OAuth1::Client.new(
140 :temporary_credential_uri =>
141 'https://www.google.com/accounts/OAuthGetRequestToken',
142 :authorization_uri =>
143 'https://www.google.com/accounts/OAuthAuthorizeToken',
144 :token_credential_uri =>
145 'https://www.google.com/accounts/OAuthGetAccessToken',
146 :client_credential_key => 'anonymous',
147 :client_credential_secret => 'anonymous'
149 when :two_legged_oauth_1, :two_legged_oauth
150 require 'signet/oauth_1/client'
151 # NOTE: Do not rely on this default value, as it may change
152 new_authorization = Signet::OAuth1::Client.new(
153 :client_credential_key => nil,
154 :client_credential_secret => nil,
158 require 'signet/oauth_2/client'
159 # NOTE: Do not rely on this default value, as it may change
160 new_authorization = Signet::OAuth2::Client.new(
161 :authorization_uri =>
162 'https://accounts.google.com/o/oauth2/auth',
163 :token_credential_uri =>
164 'https://accounts.google.com/o/oauth2/token'
167 # No authorization mechanism
169 if !new_authorization.respond_to?(:generate_authenticated_request)
171 'Expected authorization mechanism to respond to ' +
172 '#generate_authenticated_request.'
175 @authorization = new_authorization
176 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.
535 # @return [Google::APIClient::Result] The result from the API, nil if batch.
538 # result = client.execute(batch_request)
541 # plus = client.discovered_api('plus')
542 # result = client.execute(
543 # :api_method => plus.activities.list,
544 # :parameters => {'collection' => 'public', 'userId' => 'me'}
547 # @see Google::APIClient#generate_request
549 if params.first.kind_of?(Google::APIClient::Request)
550 request = params.shift
551 options = params.shift || {}
553 # This block of code allows us to accept multiple parameter passing
554 # styles, and maintaining some backwards compatibility.
556 # Note: I'm extremely tempted to deprecate this style of execute call.
557 if params.last.respond_to?(:to_hash) && params.size == 1
563 options[:api_method] = params.shift if params.size > 0
564 options[:parameters] = params.shift if params.size > 0
565 options[:body] = params.shift if params.size > 0
566 options[:headers] = params.shift if params.size > 0
567 options.update(params.shift) if params.size > 0
568 request = self.generate_request(options)
571 request.headers['User-Agent'] ||= '' + self.user_agent unless self.user_agent.nil?
572 request.parameters['key'] ||= self.key unless self.key.nil?
573 request.parameters['userIp'] ||= self.user_ip unless self.user_ip.nil?
575 connection = options[:connection] || self.connection
576 request.authorization = options[:authorization] || self.authorization unless options[:authenticated] == false
578 result = request.send(connection)
579 if result.status == 401 && request.authorization.respond_to?(:refresh_token) && auto_refresh_token
581 logger.debug("Attempting refresh of access token & retry of request")
582 request.authorization.fetch_access_token!
583 result = request.send(connection, true)
584 rescue Signet::AuthorizationError
585 # Ignore since we want the original error
593 # Same as Google::APIClient#execute, but raises an exception if there was
596 # @see Google::APIClient#execute
597 def execute!(*params)
598 result = self.execute(*params)
600 error_message = result.error_message
601 case result.response.status
603 exception_type = ClientError
604 error_message ||= "A client error has occurred."
606 exception_type = ServerError
607 error_message ||= "A server error has occurred."
609 exception_type = TransmissionError
610 error_message ||= "A transmission error has occurred."
612 raise exception_type, error_message
620 # Resolves a URI template against the client's configured base.
623 # @param [String, Addressable::URI, Addressable::Template] template
624 # The template to resolve.
625 # @param [Hash] mapping The mapping that corresponds to the template.
626 # @return [Addressable::URI] The expanded URI.
627 def resolve_uri(template, mapping={})
628 @base_uri ||= Addressable::URI.new(
633 template = if template.kind_of?(Addressable::Template)
635 elsif template.respond_to?(:to_str)
639 "Expected String, Addressable::URI, or Addressable::Template, " +
640 "got #{template.class}."
642 return Addressable::Template.new(@base_uri + template).expand(mapping)
648 require 'google/api_client/version'