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/errors'
24 require 'google/api_client/environment'
25 require 'google/api_client/discovery'
26 require 'google/api_client/request'
27 require 'google/api_client/reference'
28 require 'google/api_client/result'
29 require 'google/api_client/media'
30 require 'google/api_client/service_account'
31 require 'google/api_client/batch'
35 # This class manages APIs communication.
38 # Creates a new Google API client.
40 # @param [Hash] options The configuration parameters for the client.
41 # @option options [Symbol, #generate_authenticated_request] :authorization
43 # The authorization mechanism used by the client. The following
44 # mechanisms are supported out-of-the-box:
46 # <li><code>:two_legged_oauth_1</code></li>
47 # <li><code>:oauth_1</code></li>
48 # <li><code>:oauth_2</code></li>
50 # @option options [String] :application_name
51 # The name of the application using the client.
52 # @option options [String] :application_version
53 # The version number of the application using the client.
54 # @option options [String] :user_agent
55 # ("{app_name} google-api-ruby-client/{version} {os_name}/{os_version}")
56 # The user agent used by the client. Most developers will want to
57 # leave this value alone and use the `:application_name` option instead.
58 # @option options [String] :host ("www.googleapis.com")
59 # The API hostname used by the client. This rarely needs to be changed.
60 # @option options [String] :port (443)
61 # The port number used by the client. This rarely needs to be changed.
62 # @option options [String] :discovery_path ("/discovery/v1")
63 # The discovery base path. This rarely needs to be changed.
64 def initialize(options={})
65 # Normalize key to String to allow indifferent access.
66 options = options.inject({}) do |accu, (key, value)|
67 accu[key.to_sym] = value
70 # Almost all API usage will have a host of 'www.googleapis.com'.
71 self.host = options[:host] || 'www.googleapis.com'
72 self.port = options[:port] || 443
73 self.discovery_path = options[:discovery_path] || '/discovery/v1'
75 # Most developers will want to leave this value alone and use the
76 # application_name option.
77 application_string = (
78 options[:application_name] ? (
79 "#{options[:application_name]}/" +
80 "#{options[:application_version] || '0.0.0'}"
83 self.user_agent = options[:user_agent] || (
84 "#{application_string} " +
85 "google-api-ruby-client/#{VERSION::STRING} " +
88 # The writer method understands a few Symbols and will generate useful
89 # default authentication mechanisms.
91 options.key?(:authorization) ? options[:authorization] : :oauth_2
92 self.key = options[:key]
93 self.user_ip = options[:user_ip]
95 @discovery_documents = {}
101 # Returns the authorization mechanism used by the client.
103 # @return [#generate_authenticated_request] The authorization mechanism.
104 attr_reader :authorization
107 # Sets the authorization mechanism used by the client.
109 # @param [#generate_authenticated_request] new_authorization
110 # The new authorization mechanism.
111 def authorization=(new_authorization)
112 case new_authorization
113 when :oauth_1, :oauth
114 require 'signet/oauth_1/client'
115 # NOTE: Do not rely on this default value, as it may change
116 new_authorization = Signet::OAuth1::Client.new(
117 :temporary_credential_uri =>
118 'https://www.google.com/accounts/OAuthGetRequestToken',
119 :authorization_uri =>
120 'https://www.google.com/accounts/OAuthAuthorizeToken',
121 :token_credential_uri =>
122 'https://www.google.com/accounts/OAuthGetAccessToken',
123 :client_credential_key => 'anonymous',
124 :client_credential_secret => 'anonymous'
126 when :two_legged_oauth_1, :two_legged_oauth
127 require 'signet/oauth_1/client'
128 # NOTE: Do not rely on this default value, as it may change
129 new_authorization = Signet::OAuth1::Client.new(
130 :client_credential_key => nil,
131 :client_credential_secret => nil,
135 require 'signet/oauth_2/client'
136 # NOTE: Do not rely on this default value, as it may change
137 new_authorization = Signet::OAuth2::Client.new(
138 :authorization_uri =>
139 'https://accounts.google.com/o/oauth2/auth',
140 :token_credential_uri =>
141 'https://accounts.google.com/o/oauth2/token'
144 # No authorization mechanism
146 if !new_authorization.respond_to?(:generate_authenticated_request)
148 'Expected authorization mechanism to respond to ' +
149 '#generate_authenticated_request.'
152 @authorization = new_authorization
153 return @authorization
157 # The application's API key issued by the API console.
159 # @return [String] The API key.
163 # The IP address of the user this request is being performed on behalf of.
165 # @return [String] The user's IP address.
166 attr_accessor :user_ip
169 # The user agent used by the client.
172 # The user agent string used in the User-Agent header.
173 attr_accessor :user_agent
176 # The API hostname used by the client.
179 # The API hostname. Should almost always be 'www.googleapis.com'.
183 # The port number used by the client.
186 # The port number. Should almost always be 443.
190 # The base path used by the client for discovery.
193 # The base path. Should almost always be '/discovery/v1'.
194 attr_accessor :discovery_path
197 # Returns the URI for the directory document.
199 # @return [Addressable::URI] The URI of the directory document.
201 return resolve_uri(self.discovery_path + '/apis')
205 # Manually registers a URI as a discovery document for a specific version
208 # @param [String, Symbol] api The API name.
209 # @param [String] version The desired version of the API.
210 # @param [Addressable::URI] uri The URI of the discovery document.
211 def register_discovery_uri(api, version, uri)
213 version = version || 'v1'
214 @discovery_uris["#{api}:#{version}"] = uri
218 # Returns the URI for the discovery document.
220 # @param [String, Symbol] api The API name.
221 # @param [String] version The desired version of the API.
222 # @return [Addressable::URI] The URI of the discovery document.
223 def discovery_uri(api, version=nil)
225 version = version || 'v1'
226 return @discovery_uris["#{api}:#{version}"] ||= (
228 self.discovery_path + '/apis/{api}/{version}/rest',
236 # Manually registers a pre-loaded discovery document for a specific version
239 # @param [String, Symbol] api The API name.
240 # @param [String] version The desired version of the API.
241 # @param [String, StringIO] discovery_document
242 # The contents of the discovery document.
243 def register_discovery_document(api, version, discovery_document)
245 version = version || 'v1'
246 if discovery_document.kind_of?(StringIO)
247 discovery_document.rewind
248 discovery_document = discovery_document.string
249 elsif discovery_document.respond_to?(:to_str)
250 discovery_document = discovery_document.to_str
253 "Expected String or StringIO, got #{discovery_document.class}."
255 @discovery_documents["#{api}:#{version}"] =
256 MultiJson.load(discovery_document)
260 # Returns the parsed directory document.
262 # @return [Hash] The parsed JSON from the directory document.
263 def directory_document
264 return @directory_document ||= (begin
265 response = self.execute!(
266 :http_method => :get,
267 :uri => self.directory_uri,
268 :authenticated => false
275 # Returns the parsed discovery document.
277 # @param [String, Symbol] api The API name.
278 # @param [String] version The desired version of the API.
279 # @return [Hash] The parsed JSON from the discovery document.
280 def discovery_document(api, version=nil)
282 version = version || 'v1'
283 return @discovery_documents["#{api}:#{version}"] ||= (begin
284 response = self.execute!(
285 :http_method => :get,
286 :uri => self.discovery_uri(api, version),
287 :authenticated => false
294 # Returns all APIs published in the directory document.
296 # @return [Array] The list of available APIs.
298 @directory_apis ||= (begin
299 document_base = self.directory_uri
300 if self.directory_document && self.directory_document['items']
301 self.directory_document['items'].map do |discovery_document|
302 Google::APIClient::API.new(
314 # Returns the service object for a given service name and service version.
316 # @param [String, Symbol] api The API name.
317 # @param [String] version The desired version of the API.
319 # @return [Google::APIClient::API] The service object.
320 def discovered_api(api, version=nil)
321 if !api.kind_of?(String) && !api.kind_of?(Symbol)
323 "Expected String or Symbol, got #{api.class}."
326 version = version || 'v1'
327 return @discovered_apis["#{api}:#{version}"] ||= begin
328 document_base = self.discovery_uri(api, version)
329 discovery_document = self.discovery_document(api, version)
330 if document_base && discovery_document
331 Google::APIClient::API.new(
342 # Returns the method object for a given RPC name and service version.
344 # @param [String, Symbol] rpc_name The RPC name of the desired method.
345 # @param [String, Symbol] api The API the method is within.
346 # @param [String] version The desired version of the API.
348 # @return [Google::APIClient::Method] The method object.
349 def discovered_method(rpc_name, api, version=nil)
350 if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
352 "Expected String or Symbol, got #{rpc_name.class}."
354 rpc_name = rpc_name.to_s
356 version = version || 'v1'
357 service = self.discovered_api(api, version)
358 if service.to_h[rpc_name]
359 return service.to_h[rpc_name]
366 # Returns the service object with the highest version number.
368 # @note <em>Warning</em>: This method should be used with great care.
369 # As APIs are updated, minor differences between versions may cause
370 # incompatibilities. Requesting a specific version will avoid this issue.
372 # @param [String, Symbol] api The name of the service.
374 # @return [Google::APIClient::API] The service object.
375 def preferred_version(api)
376 if !api.kind_of?(String) && !api.kind_of?(Symbol)
378 "Expected String or Symbol, got #{api.class}."
381 return self.discovered_apis.detect do |a|
382 a.name == api && a.preferred == true
387 # Verifies an ID token against a server certificate. Used to ensure that
388 # an ID token supplied by an untrusted client-side mechanism is valid.
389 # Raises an error if the token is invalid or missing.
394 if !self.authorization.respond_to?(:id_token)
395 raise ArgumentError, (
396 "Current authorization mechanism does not support ID tokens: " +
397 "#{self.authorization.class.to_s}"
399 elsif !self.authorization.id_token
400 raise ArgumentError, (
401 "Could not verify ID token, ID token missing. " +
402 "Scopes were: #{self.authorization.scope.inspect}"
405 check_cached_certs = lambda do
407 for key, cert in @certificates
409 self.authorization.decoded_id_token(cert.public_key)
411 rescue JWT::DecodeError, Signet::UnsafeOperationError
412 # Expected exception. Ignore, ID token has not been validated.
417 if check_cached_certs.call()
420 response = self.execute!(
421 :http_method => :get,
422 :uri => 'https://www.googleapis.com/oauth2/v1/certs',
423 :authenticated => false
425 @certificates.merge!(
426 Hash[MultiJson.load(response.body).map do |key, cert|
427 [key, OpenSSL::X509::Certificate.new(cert)]
430 if check_cached_certs.call()
433 raise InvalidIDTokenError,
434 "Could not verify ID token against any available certificate."
441 # Generates a request.
443 # @option options [Google::APIClient::Method] :api_method
444 # The method object or the RPC name of the method being executed.
445 # @option options [Hash, Array] :parameters
446 # The parameters to send to the method.
447 # @option options [Hash, Array] :headers The HTTP headers for the request.
448 # @option options [String] :body The body of the request.
449 # @option options [String] :version ("v1")
450 # The service version. Only used if `api_method` is a `String`.
451 # @option options [#generate_authenticated_request] :authorization
452 # The authorization mechanism for the response. Used only if
453 # `:authenticated` is `true`.
454 # @option options [TrueClass, FalseClass] :authenticated (true)
455 # `true` if the request must be signed or somehow
456 # authenticated, `false` otherwise.
458 # @return [Google::APIClient::Reference] The generated request.
461 # request = client.generate_request(
462 # :api_method => 'plus.activities.list',
464 # {'collection' => 'public', 'userId' => 'me'}
466 def generate_request(options={})
470 return Google::APIClient::Request.new(options)
474 # Executes a request, wrapping it in a Result object.
476 # @param [Google::APIClient::Request, Hash, Array] params
477 # Either a Google::APIClient::Request, a Hash, or an Array.
479 # If a Google::APIClient::Request, no other parameters are expected.
481 # If a Hash, the below parameters are handled. If an Array, the
482 # parameters are assumed to be in the below order:
484 # - (Google::APIClient::Method) api_method:
485 # The method object or the RPC name of the method being executed.
486 # - (Hash, Array) parameters:
487 # The parameters to send to the method.
488 # - (String) body: The body of the request.
489 # - (Hash, Array) headers: The HTTP headers for the request.
490 # - (Hash) options: A set of options for the request, of which:
491 # - (#generate_authenticated_request) :authorization (default: true) -
492 # The authorization mechanism for the response. Used only if
493 # `:authenticated` is `true`.
494 # - (TrueClass, FalseClass) :authenticated (default: true) -
495 # `true` if the request must be signed or somehow
496 # authenticated, `false` otherwise.
498 # @return [Google::APIClient::Result] The result from the API, nil if batch.
501 # result = client.execute(batch_request)
504 # plus = client.discovered_api('plus')
505 # result = client.execute(
506 # :api_method => plus.activities.list,
507 # :parameters => {'collection' => 'public', 'userId' => 'me'}
510 # @see Google::APIClient#generate_request
512 if params.last.kind_of?(Google::APIClient::Request) &&
517 # This block of code allows us to accept multiple parameter passing
518 # styles, and maintaining some backwards compatibility.
520 # Note: I'm extremely tempted to deprecate this style of execute call.
521 if params.last.respond_to?(:to_hash) && params.size == 1
527 options[:api_method] = params.shift if params.size > 0
528 options[:parameters] = params.shift if params.size > 0
529 options[:body] = params.shift if params.size > 0
530 options[:headers] = params.shift if params.size > 0
531 options.update(params.shift) if params.size > 0
532 request = self.generate_request(options)
535 request.headers['User-Agent'] ||= '' + self.user_agent unless self.user_agent.nil?
536 request.parameters['key'] ||= self.key unless self.key.nil?
537 request.parameters['userIp'] ||= self.user_ip unless self.user_ip.nil?
539 connection = options[:connection] || Faraday.default_connection
540 request.authorization = options[:authorization] || self.authorization unless options[:authenticated] == false
542 result = request.send(connection)
547 # Same as Google::APIClient#execute, but raises an exception if there was
550 # @see Google::APIClient#execute
551 def execute!(*params)
552 result = self.execute(*params)
554 error_message = result.error_message
555 case result.response.status
557 exception_type = ClientError
558 error_message ||= "A client error has occurred."
560 exception_type = ServerError
561 error_message ||= "A server error has occurred."
563 exception_type = TransmissionError
564 error_message ||= "A transmission error has occurred."
566 raise exception_type, error_message
574 # Resolves a URI template against the client's configured base.
577 # @param [String, Addressable::URI, Addressable::Template] template
578 # The template to resolve.
579 # @param [Hash] mapping The mapping that corresponds to the template.
580 # @return [Addressable::URI] The expanded URI.
581 def resolve_uri(template, mapping={})
582 @base_uri ||= Addressable::URI.new(
587 template = if template.kind_of?(Addressable::Template)
589 elsif template.respond_to?(:to_str)
593 "Expected String, Addressable::URI, or Addressable::Template, " +
594 "got #{template.class}."
596 return Addressable::Template.new(@base_uri + template).expand(mapping)
602 require 'google/api_client/version'