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 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 = {}
111 self.connection = Faraday.new do |faraday|
112 faraday.options.params_encoder = Faraday::FlatParamsEncoder
113 faraday.ssl.ca_file = File.expand_path('../../cacerts.pem', __FILE__)
114 faraday.ssl.verify = true
115 faraday.adapter Faraday.default_adapter
122 # Returns the authorization mechanism used by the client.
124 # @return [#generate_authenticated_request] The authorization mechanism.
125 attr_reader :authorization
128 # Sets the authorization mechanism used by the client.
130 # @param [#generate_authenticated_request] new_authorization
131 # The new authorization mechanism.
132 def authorization=(new_authorization)
133 case new_authorization
134 when :oauth_1, :oauth
135 require 'signet/oauth_1/client'
136 # NOTE: Do not rely on this default value, as it may change
137 new_authorization = Signet::OAuth1::Client.new(
138 :temporary_credential_uri =>
139 'https://www.google.com/accounts/OAuthGetRequestToken',
140 :authorization_uri =>
141 'https://www.google.com/accounts/OAuthAuthorizeToken',
142 :token_credential_uri =>
143 'https://www.google.com/accounts/OAuthGetAccessToken',
144 :client_credential_key => 'anonymous',
145 :client_credential_secret => 'anonymous'
147 when :two_legged_oauth_1, :two_legged_oauth
148 require 'signet/oauth_1/client'
149 # NOTE: Do not rely on this default value, as it may change
150 new_authorization = Signet::OAuth1::Client.new(
151 :client_credential_key => nil,
152 :client_credential_secret => nil,
156 require 'signet/oauth_2/client'
157 # NOTE: Do not rely on this default value, as it may change
158 new_authorization = Signet::OAuth2::Client.new(
159 :authorization_uri =>
160 'https://accounts.google.com/o/oauth2/auth',
161 :token_credential_uri =>
162 'https://accounts.google.com/o/oauth2/token'
165 # No authorization mechanism
167 if !new_authorization.respond_to?(:generate_authenticated_request)
169 'Expected authorization mechanism to respond to ' +
170 '#generate_authenticated_request.'
173 @authorization = new_authorization
174 return @authorization
179 # Default Faraday/HTTP connection.
181 # @return [Faraday::Connection]
182 attr_accessor :connection
185 # The setting that controls whether or not the api client attempts to
186 # refresh authorization when a 401 is hit in #execute.
189 attr_accessor :auto_refresh_token
192 # The application's API key issued by the API console.
194 # @return [String] The API key.
198 # The IP address of the user this request is being performed on behalf of.
200 # @return [String] The user's IP address.
201 attr_accessor :user_ip
204 # The user agent used by the client.
207 # The user agent string used in the User-Agent header.
208 attr_accessor :user_agent
211 # The API hostname used by the client.
214 # The API hostname. Should almost always be 'www.googleapis.com'.
218 # The port number used by the client.
221 # The port number. Should almost always be 443.
225 # The base path used by the client for discovery.
228 # The base path. Should almost always be '/discovery/v1'.
229 attr_accessor :discovery_path
232 # Returns the URI for the directory document.
234 # @return [Addressable::URI] The URI of the directory document.
236 return resolve_uri(self.discovery_path + '/apis')
240 # Manually registers a URI as a discovery document for a specific version
243 # @param [String, Symbol] api The API name.
244 # @param [String] version The desired version of the API.
245 # @param [Addressable::URI] uri The URI of the discovery document.
246 def register_discovery_uri(api, version, uri)
248 version = version || 'v1'
249 @discovery_uris["#{api}:#{version}"] = uri
253 # Returns the URI for the discovery document.
255 # @param [String, Symbol] api The API name.
256 # @param [String] version The desired version of the API.
257 # @return [Addressable::URI] The URI of the discovery document.
258 def discovery_uri(api, version=nil)
260 version = version || 'v1'
261 return @discovery_uris["#{api}:#{version}"] ||= (
263 self.discovery_path + '/apis/{api}/{version}/rest',
271 # Manually registers a pre-loaded discovery document for a specific version
274 # @param [String, Symbol] api The API name.
275 # @param [String] version The desired version of the API.
276 # @param [String, StringIO] discovery_document
277 # The contents of the discovery document.
278 def register_discovery_document(api, version, discovery_document)
280 version = version || 'v1'
281 if discovery_document.kind_of?(StringIO)
282 discovery_document.rewind
283 discovery_document = discovery_document.string
284 elsif discovery_document.respond_to?(:to_str)
285 discovery_document = discovery_document.to_str
288 "Expected String or StringIO, got #{discovery_document.class}."
290 @discovery_documents["#{api}:#{version}"] =
291 MultiJson.load(discovery_document)
295 # Returns the parsed directory document.
297 # @return [Hash] The parsed JSON from the directory document.
298 def directory_document
299 return @directory_document ||= (begin
300 response = self.execute!(
301 :http_method => :get,
302 :uri => self.directory_uri,
303 :authenticated => false
310 # Returns the parsed discovery document.
312 # @param [String, Symbol] api The API name.
313 # @param [String] version The desired version of the API.
314 # @return [Hash] The parsed JSON from the discovery document.
315 def discovery_document(api, version=nil)
317 version = version || 'v1'
318 return @discovery_documents["#{api}:#{version}"] ||= (begin
319 response = self.execute!(
320 :http_method => :get,
321 :uri => self.discovery_uri(api, version),
322 :authenticated => false
329 # Returns all APIs published in the directory document.
331 # @return [Array] The list of available APIs.
333 @directory_apis ||= (begin
334 document_base = self.directory_uri
335 if self.directory_document && self.directory_document['items']
336 self.directory_document['items'].map do |discovery_document|
337 Google::APIClient::API.new(
349 # Returns the service object for a given service name and service version.
351 # @param [String, Symbol] api The API name.
352 # @param [String] version The desired version of the API.
354 # @return [Google::APIClient::API] The service object.
355 def discovered_api(api, version=nil)
356 if !api.kind_of?(String) && !api.kind_of?(Symbol)
358 "Expected String or Symbol, got #{api.class}."
361 version = version || 'v1'
362 return @discovered_apis["#{api}:#{version}"] ||= begin
363 document_base = self.discovery_uri(api, version)
364 discovery_document = self.discovery_document(api, version)
365 if document_base && discovery_document
366 Google::APIClient::API.new(
377 # Returns the method object for a given RPC name and service version.
379 # @param [String, Symbol] rpc_name The RPC name of the desired method.
380 # @param [String, Symbol] api The API the method is within.
381 # @param [String] version The desired version of the API.
383 # @return [Google::APIClient::Method] The method object.
384 def discovered_method(rpc_name, api, version=nil)
385 if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
387 "Expected String or Symbol, got #{rpc_name.class}."
389 rpc_name = rpc_name.to_s
391 version = version || 'v1'
392 service = self.discovered_api(api, version)
393 if service.to_h[rpc_name]
394 return service.to_h[rpc_name]
401 # Returns the service object with the highest version number.
403 # @note <em>Warning</em>: This method should be used with great care.
404 # As APIs are updated, minor differences between versions may cause
405 # incompatibilities. Requesting a specific version will avoid this issue.
407 # @param [String, Symbol] api The name of the service.
409 # @return [Google::APIClient::API] The service object.
410 def preferred_version(api)
411 if !api.kind_of?(String) && !api.kind_of?(Symbol)
413 "Expected String or Symbol, got #{api.class}."
416 return self.discovered_apis.detect do |a|
417 a.name == api && a.preferred == true
422 # Verifies an ID token against a server certificate. Used to ensure that
423 # an ID token supplied by an untrusted client-side mechanism is valid.
424 # Raises an error if the token is invalid or missing.
429 if !self.authorization.respond_to?(:id_token)
430 raise ArgumentError, (
431 "Current authorization mechanism does not support ID tokens: " +
432 "#{self.authorization.class.to_s}"
434 elsif !self.authorization.id_token
435 raise ArgumentError, (
436 "Could not verify ID token, ID token missing. " +
437 "Scopes were: #{self.authorization.scope.inspect}"
440 check_cached_certs = lambda do
442 for key, cert in @certificates
444 self.authorization.decoded_id_token(cert.public_key)
446 rescue JWT::DecodeError, Signet::UnsafeOperationError
447 # Expected exception. Ignore, ID token has not been validated.
452 if check_cached_certs.call()
455 response = self.execute!(
456 :http_method => :get,
457 :uri => 'https://www.googleapis.com/oauth2/v1/certs',
458 :authenticated => false
460 @certificates.merge!(
461 Hash[MultiJson.load(response.body).map do |key, cert|
462 [key, OpenSSL::X509::Certificate.new(cert)]
465 if check_cached_certs.call()
468 raise InvalidIDTokenError,
469 "Could not verify ID token against any available certificate."
476 # Generates a request.
478 # @option options [Google::APIClient::Method] :api_method
479 # The method object or the RPC name of the method being executed.
480 # @option options [Hash, Array] :parameters
481 # The parameters to send to the method.
482 # @option options [Hash, Array] :headers The HTTP headers for the request.
483 # @option options [String] :body The body of the request.
484 # @option options [String] :version ("v1")
485 # The service version. Only used if `api_method` is a `String`.
486 # @option options [#generate_authenticated_request] :authorization
487 # The authorization mechanism for the response. Used only if
488 # `:authenticated` is `true`.
489 # @option options [TrueClass, FalseClass] :authenticated (true)
490 # `true` if the request must be signed or somehow
491 # authenticated, `false` otherwise.
493 # @return [Google::APIClient::Reference] The generated request.
496 # request = client.generate_request(
497 # :api_method => 'plus.activities.list',
499 # {'collection' => 'public', 'userId' => 'me'}
501 def generate_request(options={})
505 return Google::APIClient::Request.new(options)
509 # Executes a request, wrapping it in a Result object.
511 # @param [Google::APIClient::Request, Hash, Array] params
512 # Either a Google::APIClient::Request, a Hash, or an Array.
514 # If a Google::APIClient::Request, no other parameters are expected.
516 # If a Hash, the below parameters are handled. If an Array, the
517 # parameters are assumed to be in the below order:
519 # - (Google::APIClient::Method) api_method:
520 # The method object or the RPC name of the method being executed.
521 # - (Hash, Array) parameters:
522 # The parameters to send to the method.
523 # - (String) body: The body of the request.
524 # - (Hash, Array) headers: The HTTP headers for the request.
525 # - (Hash) options: A set of options for the request, of which:
526 # - (#generate_authenticated_request) :authorization (default: true) -
527 # The authorization mechanism for the response. Used only if
528 # `:authenticated` is `true`.
529 # - (TrueClass, FalseClass) :authenticated (default: true) -
530 # `true` if the request must be signed or somehow
531 # authenticated, `false` otherwise.
533 # @return [Google::APIClient::Result] The result from the API, nil if batch.
536 # result = client.execute(batch_request)
539 # plus = client.discovered_api('plus')
540 # result = client.execute(
541 # :api_method => plus.activities.list,
542 # :parameters => {'collection' => 'public', 'userId' => 'me'}
545 # @see Google::APIClient#generate_request
547 if params.first.kind_of?(Google::APIClient::Request)
548 request = params.shift
549 options = params.shift || {}
551 # This block of code allows us to accept multiple parameter passing
552 # styles, and maintaining some backwards compatibility.
554 # Note: I'm extremely tempted to deprecate this style of execute call.
555 if params.last.respond_to?(:to_hash) && params.size == 1
561 options[:api_method] = params.shift if params.size > 0
562 options[:parameters] = params.shift if params.size > 0
563 options[:body] = params.shift if params.size > 0
564 options[:headers] = params.shift if params.size > 0
565 options.update(params.shift) if params.size > 0
566 request = self.generate_request(options)
569 request.headers['User-Agent'] ||= '' + self.user_agent unless self.user_agent.nil?
570 request.parameters['key'] ||= self.key unless self.key.nil?
571 request.parameters['userIp'] ||= self.user_ip unless self.user_ip.nil?
573 connection = options[:connection] || self.connection
574 request.authorization = options[:authorization] || self.authorization unless options[:authenticated] == false
576 result = request.send(connection)
577 if result.status == 401 && request.authorization.respond_to?(:refresh_token) && auto_refresh_token
579 logger.debug("Attempting refresh of access token & retry of request")
580 request.authorization.fetch_access_token!
581 result = request.send(connection)
582 rescue Signet::AuthorizationError
583 # Ignore since we want the original error
591 # Same as Google::APIClient#execute, but raises an exception if there was
594 # @see Google::APIClient#execute
595 def execute!(*params)
596 result = self.execute(*params)
598 error_message = result.error_message
599 case result.response.status
601 exception_type = ClientError
602 error_message ||= "A client error has occurred."
604 exception_type = ServerError
605 error_message ||= "A server error has occurred."
607 exception_type = TransmissionError
608 error_message ||= "A transmission error has occurred."
610 raise exception_type, error_message
618 # Resolves a URI template against the client's configured base.
621 # @param [String, Addressable::URI, Addressable::Template] template
622 # The template to resolve.
623 # @param [Hash] mapping The mapping that corresponds to the template.
624 # @return [Addressable::URI] The expanded URI.
625 def resolve_uri(template, mapping={})
626 @base_uri ||= Addressable::URI.new(
631 template = if template.kind_of?(Addressable::Template)
633 elsif template.respond_to?(:to_str)
637 "Expected String, Addressable::URI, or Addressable::Template, " +
638 "got #{template.class}."
640 return Addressable::Template.new(@base_uri + template).expand(mapping)
646 require 'google/api_client/version'