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.adapter Faraday.default_adapter
113 faraday.options.params_encoder = Faraday::FlatParamsEncoder
120 # Returns the authorization mechanism used by the client.
122 # @return [#generate_authenticated_request] The authorization mechanism.
123 attr_reader :authorization
126 # Sets the authorization mechanism used by the client.
128 # @param [#generate_authenticated_request] new_authorization
129 # The new authorization mechanism.
130 def authorization=(new_authorization)
131 case new_authorization
132 when :oauth_1, :oauth
133 require 'signet/oauth_1/client'
134 # NOTE: Do not rely on this default value, as it may change
135 new_authorization = Signet::OAuth1::Client.new(
136 :temporary_credential_uri =>
137 'https://www.google.com/accounts/OAuthGetRequestToken',
138 :authorization_uri =>
139 'https://www.google.com/accounts/OAuthAuthorizeToken',
140 :token_credential_uri =>
141 'https://www.google.com/accounts/OAuthGetAccessToken',
142 :client_credential_key => 'anonymous',
143 :client_credential_secret => 'anonymous'
145 when :two_legged_oauth_1, :two_legged_oauth
146 require 'signet/oauth_1/client'
147 # NOTE: Do not rely on this default value, as it may change
148 new_authorization = Signet::OAuth1::Client.new(
149 :client_credential_key => nil,
150 :client_credential_secret => nil,
154 require 'signet/oauth_2/client'
155 # NOTE: Do not rely on this default value, as it may change
156 new_authorization = Signet::OAuth2::Client.new(
157 :authorization_uri =>
158 'https://accounts.google.com/o/oauth2/auth',
159 :token_credential_uri =>
160 'https://accounts.google.com/o/oauth2/token'
163 # No authorization mechanism
165 if !new_authorization.respond_to?(:generate_authenticated_request)
167 'Expected authorization mechanism to respond to ' +
168 '#generate_authenticated_request.'
171 @authorization = new_authorization
172 return @authorization
177 # Default Faraday/HTTP connection.
179 # @return [Faraday::Connection]
180 attr_accessor :connection
183 # The setting that controls whether or not the api client attempts to
184 # refresh authorization when a 401 is hit in #execute.
187 attr_accessor :auto_refresh_token
190 # The application's API key issued by the API console.
192 # @return [String] The API key.
196 # The IP address of the user this request is being performed on behalf of.
198 # @return [String] The user's IP address.
199 attr_accessor :user_ip
202 # The user agent used by the client.
205 # The user agent string used in the User-Agent header.
206 attr_accessor :user_agent
209 # The API hostname used by the client.
212 # The API hostname. Should almost always be 'www.googleapis.com'.
216 # The port number used by the client.
219 # The port number. Should almost always be 443.
223 # The base path used by the client for discovery.
226 # The base path. Should almost always be '/discovery/v1'.
227 attr_accessor :discovery_path
230 # Returns the URI for the directory document.
232 # @return [Addressable::URI] The URI of the directory document.
234 return resolve_uri(self.discovery_path + '/apis')
238 # Manually registers a URI as a discovery document for a specific version
241 # @param [String, Symbol] api The API name.
242 # @param [String] version The desired version of the API.
243 # @param [Addressable::URI] uri The URI of the discovery document.
244 def register_discovery_uri(api, version, uri)
246 version = version || 'v1'
247 @discovery_uris["#{api}:#{version}"] = uri
251 # Returns the URI for the discovery document.
253 # @param [String, Symbol] api The API name.
254 # @param [String] version The desired version of the API.
255 # @return [Addressable::URI] The URI of the discovery document.
256 def discovery_uri(api, version=nil)
258 version = version || 'v1'
259 return @discovery_uris["#{api}:#{version}"] ||= (
261 self.discovery_path + '/apis/{api}/{version}/rest',
269 # Manually registers a pre-loaded discovery document for a specific version
272 # @param [String, Symbol] api The API name.
273 # @param [String] version The desired version of the API.
274 # @param [String, StringIO] discovery_document
275 # The contents of the discovery document.
276 def register_discovery_document(api, version, discovery_document)
278 version = version || 'v1'
279 if discovery_document.kind_of?(StringIO)
280 discovery_document.rewind
281 discovery_document = discovery_document.string
282 elsif discovery_document.respond_to?(:to_str)
283 discovery_document = discovery_document.to_str
286 "Expected String or StringIO, got #{discovery_document.class}."
288 @discovery_documents["#{api}:#{version}"] =
289 MultiJson.load(discovery_document)
293 # Returns the parsed directory document.
295 # @return [Hash] The parsed JSON from the directory document.
296 def directory_document
297 return @directory_document ||= (begin
298 response = self.execute!(
299 :http_method => :get,
300 :uri => self.directory_uri,
301 :authenticated => false
308 # Returns the parsed discovery document.
310 # @param [String, Symbol] api The API name.
311 # @param [String] version The desired version of the API.
312 # @return [Hash] The parsed JSON from the discovery document.
313 def discovery_document(api, version=nil)
315 version = version || 'v1'
316 return @discovery_documents["#{api}:#{version}"] ||= (begin
317 response = self.execute!(
318 :http_method => :get,
319 :uri => self.discovery_uri(api, version),
320 :authenticated => false
327 # Returns all APIs published in the directory document.
329 # @return [Array] The list of available APIs.
331 @directory_apis ||= (begin
332 document_base = self.directory_uri
333 if self.directory_document && self.directory_document['items']
334 self.directory_document['items'].map do |discovery_document|
335 Google::APIClient::API.new(
347 # Returns the service object for a given service name and service version.
349 # @param [String, Symbol] api The API name.
350 # @param [String] version The desired version of the API.
352 # @return [Google::APIClient::API] The service object.
353 def discovered_api(api, version=nil)
354 if !api.kind_of?(String) && !api.kind_of?(Symbol)
356 "Expected String or Symbol, got #{api.class}."
359 version = version || 'v1'
360 return @discovered_apis["#{api}:#{version}"] ||= begin
361 document_base = self.discovery_uri(api, version)
362 discovery_document = self.discovery_document(api, version)
363 if document_base && discovery_document
364 Google::APIClient::API.new(
375 # Returns the method object for a given RPC name and service version.
377 # @param [String, Symbol] rpc_name The RPC name of the desired method.
378 # @param [String, Symbol] api The API the method is within.
379 # @param [String] version The desired version of the API.
381 # @return [Google::APIClient::Method] The method object.
382 def discovered_method(rpc_name, api, version=nil)
383 if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
385 "Expected String or Symbol, got #{rpc_name.class}."
387 rpc_name = rpc_name.to_s
389 version = version || 'v1'
390 service = self.discovered_api(api, version)
391 if service.to_h[rpc_name]
392 return service.to_h[rpc_name]
399 # Returns the service object with the highest version number.
401 # @note <em>Warning</em>: This method should be used with great care.
402 # As APIs are updated, minor differences between versions may cause
403 # incompatibilities. Requesting a specific version will avoid this issue.
405 # @param [String, Symbol] api The name of the service.
407 # @return [Google::APIClient::API] The service object.
408 def preferred_version(api)
409 if !api.kind_of?(String) && !api.kind_of?(Symbol)
411 "Expected String or Symbol, got #{api.class}."
414 return self.discovered_apis.detect do |a|
415 a.name == api && a.preferred == true
420 # Verifies an ID token against a server certificate. Used to ensure that
421 # an ID token supplied by an untrusted client-side mechanism is valid.
422 # Raises an error if the token is invalid or missing.
427 if !self.authorization.respond_to?(:id_token)
428 raise ArgumentError, (
429 "Current authorization mechanism does not support ID tokens: " +
430 "#{self.authorization.class.to_s}"
432 elsif !self.authorization.id_token
433 raise ArgumentError, (
434 "Could not verify ID token, ID token missing. " +
435 "Scopes were: #{self.authorization.scope.inspect}"
438 check_cached_certs = lambda do
440 for key, cert in @certificates
442 self.authorization.decoded_id_token(cert.public_key)
444 rescue JWT::DecodeError, Signet::UnsafeOperationError
445 # Expected exception. Ignore, ID token has not been validated.
450 if check_cached_certs.call()
453 response = self.execute!(
454 :http_method => :get,
455 :uri => 'https://www.googleapis.com/oauth2/v1/certs',
456 :authenticated => false
458 @certificates.merge!(
459 Hash[MultiJson.load(response.body).map do |key, cert|
460 [key, OpenSSL::X509::Certificate.new(cert)]
463 if check_cached_certs.call()
466 raise InvalidIDTokenError,
467 "Could not verify ID token against any available certificate."
474 # Generates a request.
476 # @option options [Google::APIClient::Method] :api_method
477 # The method object or the RPC name of the method being executed.
478 # @option options [Hash, Array] :parameters
479 # The parameters to send to the method.
480 # @option options [Hash, Array] :headers The HTTP headers for the request.
481 # @option options [String] :body The body of the request.
482 # @option options [String] :version ("v1")
483 # The service version. Only used if `api_method` is a `String`.
484 # @option options [#generate_authenticated_request] :authorization
485 # The authorization mechanism for the response. Used only if
486 # `:authenticated` is `true`.
487 # @option options [TrueClass, FalseClass] :authenticated (true)
488 # `true` if the request must be signed or somehow
489 # authenticated, `false` otherwise.
491 # @return [Google::APIClient::Reference] The generated request.
494 # request = client.generate_request(
495 # :api_method => 'plus.activities.list',
497 # {'collection' => 'public', 'userId' => 'me'}
499 def generate_request(options={})
503 return Google::APIClient::Request.new(options)
507 # Executes a request, wrapping it in a Result object.
509 # @param [Google::APIClient::Request, Hash, Array] params
510 # Either a Google::APIClient::Request, a Hash, or an Array.
512 # If a Google::APIClient::Request, no other parameters are expected.
514 # If a Hash, the below parameters are handled. If an Array, the
515 # parameters are assumed to be in the below order:
517 # - (Google::APIClient::Method) api_method:
518 # The method object or the RPC name of the method being executed.
519 # - (Hash, Array) parameters:
520 # The parameters to send to the method.
521 # - (String) body: The body of the request.
522 # - (Hash, Array) headers: The HTTP headers for the request.
523 # - (Hash) options: A set of options for the request, of which:
524 # - (#generate_authenticated_request) :authorization (default: true) -
525 # The authorization mechanism for the response. Used only if
526 # `:authenticated` is `true`.
527 # - (TrueClass, FalseClass) :authenticated (default: true) -
528 # `true` if the request must be signed or somehow
529 # authenticated, `false` otherwise.
531 # @return [Google::APIClient::Result] The result from the API, nil if batch.
534 # result = client.execute(batch_request)
537 # plus = client.discovered_api('plus')
538 # result = client.execute(
539 # :api_method => plus.activities.list,
540 # :parameters => {'collection' => 'public', 'userId' => 'me'}
543 # @see Google::APIClient#generate_request
545 if params.first.kind_of?(Google::APIClient::Request)
546 request = params.shift
547 options = params.shift || {}
549 # This block of code allows us to accept multiple parameter passing
550 # styles, and maintaining some backwards compatibility.
552 # Note: I'm extremely tempted to deprecate this style of execute call.
553 if params.last.respond_to?(:to_hash) && params.size == 1
559 options[:api_method] = params.shift if params.size > 0
560 options[:parameters] = params.shift if params.size > 0
561 options[:body] = params.shift if params.size > 0
562 options[:headers] = params.shift if params.size > 0
563 options.update(params.shift) if params.size > 0
564 request = self.generate_request(options)
567 request.headers['User-Agent'] ||= '' + self.user_agent unless self.user_agent.nil?
568 request.parameters['key'] ||= self.key unless self.key.nil?
569 request.parameters['userIp'] ||= self.user_ip unless self.user_ip.nil?
571 connection = options[:connection] || self.connection
572 request.authorization = options[:authorization] || self.authorization unless options[:authenticated] == false
574 result = request.send(connection)
575 if result.status == 401 && request.authorization.respond_to?(:refresh_token) && auto_refresh_token
577 logger.debug("Attempting refresh of access token & retry of request")
578 request.authorization.fetch_access_token!
579 result = request.send(connection)
580 rescue Signet::AuthorizationError
581 # Ignore since we want the original error
589 # Same as Google::APIClient#execute, but raises an exception if there was
592 # @see Google::APIClient#execute
593 def execute!(*params)
594 result = self.execute(*params)
596 error_message = result.error_message
597 case result.response.status
599 exception_type = ClientError
600 error_message ||= "A client error has occurred."
602 exception_type = ServerError
603 error_message ||= "A server error has occurred."
605 exception_type = TransmissionError
606 error_message ||= "A transmission error has occurred."
608 raise exception_type, error_message
616 # Resolves a URI template against the client's configured base.
619 # @param [String, Addressable::URI, Addressable::Template] template
620 # The template to resolve.
621 # @param [Hash] mapping The mapping that corresponds to the template.
622 # @return [Addressable::URI] The expanded URI.
623 def resolve_uri(template, mapping={})
624 @base_uri ||= Addressable::URI.new(
629 template = if template.kind_of?(Addressable::Template)
631 elsif template.respond_to?(:to_str)
635 "Expected String, Addressable::URI, or Addressable::Template, " +
636 "got #{template.class}."
638 return Addressable::Template.new(@base_uri + template).expand(mapping)
644 require 'google/api_client/version'