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/logging'
23 require 'google/api_client/version'
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::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 # Normalize key to String to allow indifferent access.
75 options = options.inject({}) do |accu, (key, value)|
76 accu[key.to_sym] = value
79 # Almost all API usage will have a host of 'www.googleapis.com'.
80 self.host = options[:host] || 'www.googleapis.com'
81 self.port = options[:port] || 443
82 self.discovery_path = options[:discovery_path] || '/discovery/v1'
84 # Most developers will want to leave this value alone and use the
85 # application_name option.
86 if options[:application_name]
87 app_name = options[:application_name]
88 app_version = options[:application_version]
89 application_string = "#{app_name}/#{app_version || '0.0.0'}"
91 logger.warn("Please provide :application_name and :application_version when initializing the APIClient")
93 self.user_agent = options[:user_agent] || (
94 "#{application_string} " +
95 "google-api-ruby-client/#{VERSION::STRING} " +
98 # The writer method understands a few Symbols and will generate useful
99 # default authentication mechanisms.
101 options.key?(:authorization) ? options[:authorization] : :oauth_2
102 self.auto_refresh_token = options.fetch(:auto_refresh_token){ true }
103 self.key = options[:key]
104 self.user_ip = options[:user_ip]
106 @discovery_documents = {}
107 @discovered_apis = {}
112 # Returns the authorization mechanism used by the client.
114 # @return [#generate_authenticated_request] The authorization mechanism.
115 attr_reader :authorization
118 # Sets the authorization mechanism used by the client.
120 # @param [#generate_authenticated_request] new_authorization
121 # The new authorization mechanism.
122 def authorization=(new_authorization)
123 case new_authorization
124 when :oauth_1, :oauth
125 require 'signet/oauth_1/client'
126 # NOTE: Do not rely on this default value, as it may change
127 new_authorization = Signet::OAuth1::Client.new(
128 :temporary_credential_uri =>
129 'https://www.google.com/accounts/OAuthGetRequestToken',
130 :authorization_uri =>
131 'https://www.google.com/accounts/OAuthAuthorizeToken',
132 :token_credential_uri =>
133 'https://www.google.com/accounts/OAuthGetAccessToken',
134 :client_credential_key => 'anonymous',
135 :client_credential_secret => 'anonymous'
137 when :two_legged_oauth_1, :two_legged_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 :client_credential_key => nil,
142 :client_credential_secret => nil,
146 require 'signet/oauth_2/client'
147 # NOTE: Do not rely on this default value, as it may change
148 new_authorization = Signet::OAuth2::Client.new(
149 :authorization_uri =>
150 'https://accounts.google.com/o/oauth2/auth',
151 :token_credential_uri =>
152 'https://accounts.google.com/o/oauth2/token'
155 # No authorization mechanism
157 if !new_authorization.respond_to?(:generate_authenticated_request)
159 'Expected authorization mechanism to respond to ' +
160 '#generate_authenticated_request.'
163 @authorization = new_authorization
164 return @authorization
168 # The application's API key issued by the API console.
170 # @return [String] The API key.
174 # The setting that controls whether or not the api client attempts to
175 # refresh authorization when a 401 is hit in #execute.
178 attr_accessor :auto_refresh_token
181 # The IP address of the user this request is being performed on behalf of.
183 # @return [String] The user's IP address.
184 attr_accessor :user_ip
187 # The user agent used by the client.
190 # The user agent string used in the User-Agent header.
191 attr_accessor :user_agent
194 # The API hostname used by the client.
197 # The API hostname. Should almost always be 'www.googleapis.com'.
201 # The port number used by the client.
204 # The port number. Should almost always be 443.
208 # The base path used by the client for discovery.
211 # The base path. Should almost always be '/discovery/v1'.
212 attr_accessor :discovery_path
215 # Returns the URI for the directory document.
217 # @return [Addressable::URI] The URI of the directory document.
219 return resolve_uri(self.discovery_path + '/apis')
223 # Manually registers a URI as a discovery document for a specific version
226 # @param [String, Symbol] api The API name.
227 # @param [String] version The desired version of the API.
228 # @param [Addressable::URI] uri The URI of the discovery document.
229 def register_discovery_uri(api, version, uri)
231 version = version || 'v1'
232 @discovery_uris["#{api}:#{version}"] = uri
236 # Returns the URI for the discovery document.
238 # @param [String, Symbol] api The API name.
239 # @param [String] version The desired version of the API.
240 # @return [Addressable::URI] The URI of the discovery document.
241 def discovery_uri(api, version=nil)
243 version = version || 'v1'
244 return @discovery_uris["#{api}:#{version}"] ||= (
246 self.discovery_path + '/apis/{api}/{version}/rest',
254 # Manually registers a pre-loaded discovery document for a specific version
257 # @param [String, Symbol] api The API name.
258 # @param [String] version The desired version of the API.
259 # @param [String, StringIO] discovery_document
260 # The contents of the discovery document.
261 def register_discovery_document(api, version, discovery_document)
263 version = version || 'v1'
264 if discovery_document.kind_of?(StringIO)
265 discovery_document.rewind
266 discovery_document = discovery_document.string
267 elsif discovery_document.respond_to?(:to_str)
268 discovery_document = discovery_document.to_str
271 "Expected String or StringIO, got #{discovery_document.class}."
273 @discovery_documents["#{api}:#{version}"] =
274 MultiJson.load(discovery_document)
278 # Returns the parsed directory document.
280 # @return [Hash] The parsed JSON from the directory document.
281 def directory_document
282 return @directory_document ||= (begin
283 response = self.execute!(
284 :http_method => :get,
285 :uri => self.directory_uri,
286 :authenticated => false
293 # Returns the parsed discovery document.
295 # @param [String, Symbol] api The API name.
296 # @param [String] version The desired version of the API.
297 # @return [Hash] The parsed JSON from the discovery document.
298 def discovery_document(api, version=nil)
300 version = version || 'v1'
301 return @discovery_documents["#{api}:#{version}"] ||= (begin
302 response = self.execute!(
303 :http_method => :get,
304 :uri => self.discovery_uri(api, version),
305 :authenticated => false
312 # Returns all APIs published in the directory document.
314 # @return [Array] The list of available APIs.
316 @directory_apis ||= (begin
317 document_base = self.directory_uri
318 if self.directory_document && self.directory_document['items']
319 self.directory_document['items'].map do |discovery_document|
320 Google::APIClient::API.new(
332 # Returns the service object for a given service name and service version.
334 # @param [String, Symbol] api The API name.
335 # @param [String] version The desired version of the API.
337 # @return [Google::APIClient::API] The service object.
338 def discovered_api(api, version=nil)
339 if !api.kind_of?(String) && !api.kind_of?(Symbol)
341 "Expected String or Symbol, got #{api.class}."
344 version = version || 'v1'
345 return @discovered_apis["#{api}:#{version}"] ||= begin
346 document_base = self.discovery_uri(api, version)
347 discovery_document = self.discovery_document(api, version)
348 if document_base && discovery_document
349 Google::APIClient::API.new(
360 # Returns the method object for a given RPC name and service version.
362 # @param [String, Symbol] rpc_name The RPC name of the desired method.
363 # @param [String, Symbol] api The API the method is within.
364 # @param [String] version The desired version of the API.
366 # @return [Google::APIClient::Method] The method object.
367 def discovered_method(rpc_name, api, version=nil)
368 if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
370 "Expected String or Symbol, got #{rpc_name.class}."
372 rpc_name = rpc_name.to_s
374 version = version || 'v1'
375 service = self.discovered_api(api, version)
376 if service.to_h[rpc_name]
377 return service.to_h[rpc_name]
384 # Returns the service object with the highest version number.
386 # @note <em>Warning</em>: This method should be used with great care.
387 # As APIs are updated, minor differences between versions may cause
388 # incompatibilities. Requesting a specific version will avoid this issue.
390 # @param [String, Symbol] api The name of the service.
392 # @return [Google::APIClient::API] The service object.
393 def preferred_version(api)
394 if !api.kind_of?(String) && !api.kind_of?(Symbol)
396 "Expected String or Symbol, got #{api.class}."
399 return self.discovered_apis.detect do |a|
400 a.name == api && a.preferred == true
405 # Verifies an ID token against a server certificate. Used to ensure that
406 # an ID token supplied by an untrusted client-side mechanism is valid.
407 # Raises an error if the token is invalid or missing.
412 if !self.authorization.respond_to?(:id_token)
413 raise ArgumentError, (
414 "Current authorization mechanism does not support ID tokens: " +
415 "#{self.authorization.class.to_s}"
417 elsif !self.authorization.id_token
418 raise ArgumentError, (
419 "Could not verify ID token, ID token missing. " +
420 "Scopes were: #{self.authorization.scope.inspect}"
423 check_cached_certs = lambda do
425 for key, cert in @certificates
427 self.authorization.decoded_id_token(cert.public_key)
429 rescue JWT::DecodeError, Signet::UnsafeOperationError
430 # Expected exception. Ignore, ID token has not been validated.
435 if check_cached_certs.call()
438 response = self.execute!(
439 :http_method => :get,
440 :uri => 'https://www.googleapis.com/oauth2/v1/certs',
441 :authenticated => false
443 @certificates.merge!(
444 Hash[MultiJson.load(response.body).map do |key, cert|
445 [key, OpenSSL::X509::Certificate.new(cert)]
448 if check_cached_certs.call()
451 raise InvalidIDTokenError,
452 "Could not verify ID token against any available certificate."
459 # Generates a request.
461 # @option options [Google::APIClient::Method] :api_method
462 # The method object or the RPC name of the method being executed.
463 # @option options [Hash, Array] :parameters
464 # The parameters to send to the method.
465 # @option options [Hash, Array] :headers The HTTP headers for the request.
466 # @option options [String] :body The body of the request.
467 # @option options [String] :version ("v1")
468 # The service version. Only used if `api_method` is a `String`.
469 # @option options [#generate_authenticated_request] :authorization
470 # The authorization mechanism for the response. Used only if
471 # `:authenticated` is `true`.
472 # @option options [TrueClass, FalseClass] :authenticated (true)
473 # `true` if the request must be signed or somehow
474 # authenticated, `false` otherwise.
476 # @return [Google::APIClient::Reference] The generated request.
479 # request = client.generate_request(
480 # :api_method => 'plus.activities.list',
482 # {'collection' => 'public', 'userId' => 'me'}
484 def generate_request(options={})
488 return Google::APIClient::Request.new(options)
492 # Executes a request, wrapping it in a Result object.
494 # @param [Google::APIClient::Request, Hash, Array] params
495 # Either a Google::APIClient::Request, a Hash, or an Array.
497 # If a Google::APIClient::Request, no other parameters are expected.
499 # If a Hash, the below parameters are handled. If an Array, the
500 # parameters are assumed to be in the below order:
502 # - (Google::APIClient::Method) api_method:
503 # The method object or the RPC name of the method being executed.
504 # - (Hash, Array) parameters:
505 # The parameters to send to the method.
506 # - (String) body: The body of the request.
507 # - (Hash, Array) headers: The HTTP headers for the request.
508 # - (Hash) options: A set of options for the request, of which:
509 # - (#generate_authenticated_request) :authorization (default: true) -
510 # The authorization mechanism for the response. Used only if
511 # `:authenticated` is `true`.
512 # - (TrueClass, FalseClass) :authenticated (default: true) -
513 # `true` if the request must be signed or somehow
514 # authenticated, `false` otherwise.
516 # @return [Google::APIClient::Result] The result from the API, nil if batch.
519 # result = client.execute(batch_request)
522 # plus = client.discovered_api('plus')
523 # result = client.execute(
524 # :api_method => plus.activities.list,
525 # :parameters => {'collection' => 'public', 'userId' => 'me'}
528 # @see Google::APIClient#generate_request
530 if params.last.kind_of?(Google::APIClient::Request) &&
535 # This block of code allows us to accept multiple parameter passing
536 # styles, and maintaining some backwards compatibility.
538 # Note: I'm extremely tempted to deprecate this style of execute call.
539 if params.last.respond_to?(:to_hash) && params.size == 1
545 options[:api_method] = params.shift if params.size > 0
546 options[:parameters] = params.shift if params.size > 0
547 options[:body] = params.shift if params.size > 0
548 options[:headers] = params.shift if params.size > 0
549 options.update(params.shift) if params.size > 0
550 request = self.generate_request(options)
553 request.headers['User-Agent'] ||= '' + self.user_agent unless self.user_agent.nil?
554 request.parameters['key'] ||= self.key unless self.key.nil?
555 request.parameters['userIp'] ||= self.user_ip unless self.user_ip.nil?
557 connection = options[:connection] || Faraday.default_connection
558 request.authorization = options[:authorization] || self.authorization unless options[:authenticated] == false
560 result = request.send(connection)
561 if result.status == 401 && authorization.respond_to?(:refresh_token) && auto_refresh_token
563 authorization.fetch_access_token!
564 result = request.send(connection)
565 rescue Signet::AuthorizationError
566 # Ignore since we want the original error
574 # Same as Google::APIClient#execute, but raises an exception if there was
577 # @see Google::APIClient#execute
578 def execute!(*params)
579 result = self.execute(*params)
581 error_message = result.error_message
582 case result.response.status
584 exception_type = ClientError
585 error_message ||= "A client error has occurred."
587 exception_type = ServerError
588 error_message ||= "A server error has occurred."
590 exception_type = TransmissionError
591 error_message ||= "A transmission error has occurred."
593 raise exception_type, error_message
601 # Resolves a URI template against the client's configured base.
604 # @param [String, Addressable::URI, Addressable::Template] template
605 # The template to resolve.
606 # @param [Hash] mapping The mapping that corresponds to the template.
607 # @return [Addressable::URI] The expanded URI.
608 def resolve_uri(template, mapping={})
609 @base_uri ||= Addressable::URI.new(
614 template = if template.kind_of?(Addressable::Template)
616 elsif template.respond_to?(:to_str)
620 "Expected String, Addressable::URI, or Addressable::Template, " +
621 "got #{template.class}."
623 return Addressable::Template.new(@base_uri + template).expand(mapping)
629 require 'google/api_client/version'