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/reference'
27 require 'google/api_client/result'
28 require 'google/api_client/media'
29 require 'google/api_client/service_account'
30 require 'google/api_client/batch'
34 # This class manages APIs communication.
37 # Creates a new Google API client.
39 # @param [Hash] options The configuration parameters for the client.
40 # @option options [Symbol, #generate_authenticated_request] :authorization
42 # The authorization mechanism used by the client. The following
43 # mechanisms are supported out-of-the-box:
45 # <li><code>:two_legged_oauth_1</code></li>
46 # <li><code>:oauth_1</code></li>
47 # <li><code>:oauth_2</code></li>
49 # @option options [String] :application_name
50 # The name of the application using the client.
51 # @option options [String] :application_version
52 # The version number of the application using the client.
53 # @option options [String] :user_agent
54 # ("{app_name} google-api-ruby-client/{version} {os_name}/{os_version}")
55 # The user agent used by the client. Most developers will want to
56 # leave this value alone and use the `:application_name` option instead.
57 # @option options [String] :host ("www.googleapis.com")
58 # The API hostname used by the client. This rarely needs to be changed.
59 # @option options [String] :port (443)
60 # The port number used by the client. This rarely needs to be changed.
61 # @option options [String] :discovery_path ("/discovery/v1")
62 # The discovery base path. This rarely needs to be changed.
63 def initialize(options={})
64 # Normalize key to String to allow indifferent access.
65 options = options.inject({}) do |accu, (key, value)|
66 accu[key.to_sym] = value
69 # Almost all API usage will have a host of 'www.googleapis.com'.
70 self.host = options[:host] || 'www.googleapis.com'
71 self.port = options[:port] || 443
72 self.discovery_path = options[:discovery_path] || '/discovery/v1'
74 # Most developers will want to leave this value alone and use the
75 # application_name option.
76 application_string = (
77 options[:application_name] ? (
78 "#{options[:application_name]}/" +
79 "#{options[:application_version] || '0.0.0'}"
82 self.user_agent = options[:user_agent] || (
83 "#{application_string} " +
84 "google-api-ruby-client/#{VERSION::STRING} " +
87 # The writer method understands a few Symbols and will generate useful
88 # default authentication mechanisms.
90 options.key?(:authorization) ? options[:authorization] : :oauth_2
91 self.key = options[:key]
92 self.user_ip = options[:user_ip]
94 @discovery_documents = {}
100 # Returns the authorization mechanism used by the client.
102 # @return [#generate_authenticated_request] The authorization mechanism.
103 attr_reader :authorization
106 # Sets the authorization mechanism used by the client.
108 # @param [#generate_authenticated_request] new_authorization
109 # The new authorization mechanism.
110 def authorization=(new_authorization)
111 case new_authorization
112 when :oauth_1, :oauth
113 require 'signet/oauth_1/client'
114 # NOTE: Do not rely on this default value, as it may change
115 new_authorization = Signet::OAuth1::Client.new(
116 :temporary_credential_uri =>
117 'https://www.google.com/accounts/OAuthGetRequestToken',
118 :authorization_uri =>
119 'https://www.google.com/accounts/OAuthAuthorizeToken',
120 :token_credential_uri =>
121 'https://www.google.com/accounts/OAuthGetAccessToken',
122 :client_credential_key => 'anonymous',
123 :client_credential_secret => 'anonymous'
125 when :two_legged_oauth_1, :two_legged_oauth
126 require 'signet/oauth_1/client'
127 # NOTE: Do not rely on this default value, as it may change
128 new_authorization = Signet::OAuth1::Client.new(
129 :client_credential_key => nil,
130 :client_credential_secret => nil,
134 require 'signet/oauth_2/client'
135 # NOTE: Do not rely on this default value, as it may change
136 new_authorization = Signet::OAuth2::Client.new(
137 :authorization_uri =>
138 'https://accounts.google.com/o/oauth2/auth',
139 :token_credential_uri =>
140 'https://accounts.google.com/o/oauth2/token'
143 # No authorization mechanism
145 if !new_authorization.respond_to?(:generate_authenticated_request)
147 'Expected authorization mechanism to respond to ' +
148 '#generate_authenticated_request.'
151 @authorization = new_authorization
152 return @authorization
156 # The application's API key issued by the API console.
158 # @return [String] The API key.
162 # The IP address of the user this request is being performed on behalf of.
164 # @return [String] The user's IP address.
165 attr_accessor :user_ip
168 # The user agent used by the client.
171 # The user agent string used in the User-Agent header.
172 attr_accessor :user_agent
175 # The API hostname used by the client.
178 # The API hostname. Should almost always be 'www.googleapis.com'.
182 # The port number used by the client.
185 # The port number. Should almost always be 443.
189 # The base path used by the client for discovery.
192 # The base path. Should almost always be '/discovery/v1'.
193 attr_accessor :discovery_path
196 # Returns the URI for the directory document.
198 # @return [Addressable::URI] The URI of the directory document.
200 return resolve_uri(self.discovery_path + '/apis')
204 # Manually registers a URI as a discovery document for a specific version
207 # @param [String, Symbol] api The API name.
208 # @param [String] version The desired version of the API.
209 # @param [Addressable::URI] uri The URI of the discovery document.
210 def register_discovery_uri(api, version, uri)
212 version = version || 'v1'
213 @discovery_uris["#{api}:#{version}"] = uri
217 # Returns the URI for the discovery document.
219 # @param [String, Symbol] api The API name.
220 # @param [String] version The desired version of the API.
221 # @return [Addressable::URI] The URI of the discovery document.
222 def discovery_uri(api, version=nil)
224 version = version || 'v1'
225 return @discovery_uris["#{api}:#{version}"] ||= (
227 self.discovery_path + '/apis/{api}/{version}/rest',
235 # Manually registers a pre-loaded discovery document for a specific version
238 # @param [String, Symbol] api The API name.
239 # @param [String] version The desired version of the API.
240 # @param [String, StringIO] discovery_document
241 # The contents of the discovery document.
242 def register_discovery_document(api, version, discovery_document)
244 version = version || 'v1'
245 if discovery_document.kind_of?(StringIO)
246 discovery_document.rewind
247 discovery_document = discovery_document.string
248 elsif discovery_document.respond_to?(:to_str)
249 discovery_document = discovery_document.to_str
252 "Expected String or StringIO, got #{discovery_document.class}."
254 @discovery_documents["#{api}:#{version}"] =
255 MultiJson.load(discovery_document)
259 # Returns the parsed directory document.
261 # @return [Hash] The parsed JSON from the directory document.
262 def directory_document
263 return @directory_document ||= (begin
264 response = self.execute!(
265 :http_method => :get,
266 :uri => self.directory_uri,
267 :authenticated => false
274 # Returns the parsed discovery document.
276 # @param [String, Symbol] api The API name.
277 # @param [String] version The desired version of the API.
278 # @return [Hash] The parsed JSON from the discovery document.
279 def discovery_document(api, version=nil)
281 version = version || 'v1'
282 return @discovery_documents["#{api}:#{version}"] ||= (begin
283 response = self.execute!(
284 :http_method => :get,
285 :uri => self.discovery_uri(api, version),
286 :authenticated => false
293 # Returns all APIs published in the directory document.
295 # @return [Array] The list of available APIs.
297 @directory_apis ||= (begin
298 document_base = self.directory_uri
299 if self.directory_document && self.directory_document['items']
300 self.directory_document['items'].map do |discovery_document|
301 Google::APIClient::API.new(
313 # Returns the service object for a given service name and service version.
315 # @param [String, Symbol] api The API name.
316 # @param [String] version The desired version of the API.
318 # @return [Google::APIClient::API] The service object.
319 def discovered_api(api, version=nil)
320 if !api.kind_of?(String) && !api.kind_of?(Symbol)
322 "Expected String or Symbol, got #{api.class}."
325 version = version || 'v1'
326 return @discovered_apis["#{api}:#{version}"] ||= begin
327 document_base = self.discovery_uri(api, version)
328 discovery_document = self.discovery_document(api, version)
329 if document_base && discovery_document
330 Google::APIClient::API.new(
341 # Returns the method object for a given RPC name and service version.
343 # @param [String, Symbol] rpc_name The RPC name of the desired method.
344 # @param [String, Symbol] api The API the method is within.
345 # @param [String] version The desired version of the API.
347 # @return [Google::APIClient::Method] The method object.
348 def discovered_method(rpc_name, api, version=nil)
349 if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
351 "Expected String or Symbol, got #{rpc_name.class}."
353 rpc_name = rpc_name.to_s
355 version = version || 'v1'
356 service = self.discovered_api(api, version)
357 if service.to_h[rpc_name]
358 return service.to_h[rpc_name]
365 # Returns the service object with the highest version number.
367 # @note <em>Warning</em>: This method should be used with great care.
368 # As APIs are updated, minor differences between versions may cause
369 # incompatibilities. Requesting a specific version will avoid this issue.
371 # @param [String, Symbol] api The name of the service.
373 # @return [Google::APIClient::API] The service object.
374 def preferred_version(api)
375 if !api.kind_of?(String) && !api.kind_of?(Symbol)
377 "Expected String or Symbol, got #{api.class}."
380 return self.discovered_apis.detect do |a|
381 a.name == api && a.preferred == true
386 # Verifies an ID token against a server certificate. Used to ensure that
387 # an ID token supplied by an untrusted client-side mechanism is valid.
388 # Raises an error if the token is invalid or missing.
393 if !self.authorization.respond_to?(:id_token)
394 raise ArgumentError, (
395 "Current authorization mechanism does not support ID tokens: " +
396 "#{self.authorization.class.to_s}"
398 elsif !self.authorization.id_token
399 raise ArgumentError, (
400 "Could not verify ID token, ID token missing. " +
401 "Scopes were: #{self.authorization.scope.inspect}"
404 check_cached_certs = lambda do
406 for key, cert in @certificates
408 self.authorization.decoded_id_token(cert.public_key)
410 rescue JWT::DecodeError, Signet::UnsafeOperationError
411 # Expected exception. Ignore, ID token has not been validated.
416 if check_cached_certs.call()
419 response = self.execute!(
420 :http_method => :get,
421 :uri => 'https://www.googleapis.com/oauth2/v1/certs',
422 :authenticated => false
424 @certificates.merge!(
425 Hash[MultiJson.load(response.body).map do |key, cert|
426 [key, OpenSSL::X509::Certificate.new(cert)]
429 if check_cached_certs.call()
432 raise InvalidIDTokenError,
433 "Could not verify ID token against any available certificate."
440 # Generates a request.
442 # @option options [Google::APIClient::Method] :api_method
443 # The method object or the RPC name of the method being executed.
444 # @option options [Hash, Array] :parameters
445 # The parameters to send to the method.
446 # @option options [Hash, Array] :headers The HTTP headers for the request.
447 # @option options [String] :body The body of the request.
448 # @option options [String] :version ("v1")
449 # The service version. Only used if `api_method` is a `String`.
450 # @option options [#generate_authenticated_request] :authorization
451 # The authorization mechanism for the response. Used only if
452 # `:authenticated` is `true`.
453 # @option options [TrueClass, FalseClass] :authenticated (true)
454 # `true` if the request must be signed or somehow
455 # authenticated, `false` otherwise.
457 # @return [Google::APIClient::Reference] The generated request.
460 # request = client.generate_request(
461 # :api_method => 'plus.activities.list',
463 # {'collection' => 'public', 'userId' => 'me'}
465 def generate_request(options={})
469 return Google::APIClient::Request.new(options)
473 # Executes a request, wrapping it in a Result object.
475 # @param [Google::APIClient::Request, Hash, Array] params
476 # Either a Google::APIClient::Request, a Hash, or an Array.
478 # If a Google::APIClient::Request, no other parameters are expected.
480 # If a Hash, the below parameters are handled. If an Array, the
481 # parameters are assumed to be in the below order:
483 # - (Google::APIClient::Method) api_method:
484 # The method object or the RPC name of the method being executed.
485 # - (Hash, Array) parameters:
486 # The parameters to send to the method.
487 # - (String) body: The body of the request.
488 # - (Hash, Array) headers: The HTTP headers for the request.
489 # - (Hash) options: A set of options for the request, of which:
490 # - (String) :version (default: "v1") -
491 # The service version. Only used if `api_method` is a `String`.
492 # - (#generate_authenticated_request) :authorization (default: true) -
493 # The authorization mechanism for the response. Used only if
494 # `:authenticated` is `true`.
495 # - (TrueClass, FalseClass) :authenticated (default: true) -
496 # `true` if the request must be signed or somehow
497 # authenticated, `false` otherwise.
499 # @return [Google::APIClient::Result] The result from the API, nil if batch.
502 # result = client.execute(batch_request)
505 # plus = client.discovered_api('plus')
506 # result = client.execute(
507 # :api_method => plus.activities.list,
508 # :parameters => {'collection' => 'public', 'userId' => 'me'}
511 # @see Google::APIClient#generate_request
513 if params.last.kind_of?(Google::APIClient::Request) &&
518 # This block of code allows us to accept multiple parameter passing
519 # styles, and maintaining some backwards compatibility.
521 # Note: I'm extremely tempted to deprecate this style of execute call.
522 if params.last.respond_to?(:to_hash) && params.size == 1
528 options[:api_method] = params.shift if params.size > 0
529 options[:parameters] = params.shift if params.size > 0
530 options[:body] = params.shift if params.size > 0
531 options[:headers] = params.shift if params.size > 0
532 options[:client] = self
533 request = self.generate_request(options)
536 request.headers['User-Agent'] ||= '' + self.user_agent unless self.user_agent.nil?
537 request.parameters['key'] ||= self.key unless self.key.nil?
538 request.parameters['userIp'] ||= self.user_ip unless self.user_ip.nil?
540 connection = options[:connection] || Faraday.default_connection
541 request.authorization = options[:authorization] || self.authorization unless options[:authenticated] == false
543 result = request.send(connection)
548 # Same as Google::APIClient#execute, but raises an exception if there was
551 # @see Google::APIClient#execute
552 def execute!(*params)
553 result = self.execute(*params)
555 error_message = result.error_message
556 case result.response.status
558 exception_type = ClientError
559 error_message ||= "A client error has occurred."
561 exception_type = ServerError
562 error_message ||= "A server error has occurred."
564 exception_type = TransmissionError
565 error_message ||= "A transmission error has occurred."
567 raise exception_type, error_message
575 # Resolves a URI template against the client's configured base.
578 # @param [String, Addressable::URI, Addressable::Template] template
579 # The template to resolve.
580 # @param [Hash] mapping The mapping that corresponds to the template.
581 # @return [Addressable::URI] The expanded URI.
582 def resolve_uri(template, mapping={})
583 @base_uri ||= Addressable::URI.new(
588 template = if template.kind_of?(Addressable::Template)
590 elsif template.respond_to?(:to_str)
594 "Expected String, Addressable::URI, or Addressable::Template, " +
595 "got #{template.class}."
597 return Addressable::Template.new(@base_uri + template).expand(mapping)
603 require 'google/api_client/version'