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.
16 gem 'faraday', '~> 0.8.1'
18 require 'faraday/utils'
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'
33 # TODO(bobaman): Document all this stuff.
37 # This class manages APIs communication.
40 # Creates a new Google API client.
42 # @param [Hash] options The configuration parameters for the client.
43 # @option options [Symbol, #generate_authenticated_request] :authorization
45 # The authorization mechanism used by the client. The following
46 # mechanisms are supported out-of-the-box:
48 # <li><code>:two_legged_oauth_1</code></li>
49 # <li><code>:oauth_1</code></li>
50 # <li><code>:oauth_2</code></li>
52 # @option options [String] :application_name
53 # The name of the application using the client.
54 # @option options [String] :application_version
55 # The version number of the application using the client.
56 # @option options [String] :user_agent
57 # ("{app_name} google-api-ruby-client/{version} {os_name}/{os_version}")
58 # The user agent used by the client. Most developers will want to
59 # leave this value alone and use the `:application_name` option instead.
60 # @option options [String] :host ("www.googleapis.com")
61 # The API hostname used by the client. This rarely needs to be changed.
62 # @option options [String] :port (443)
63 # The port number used by the client. This rarely needs to be changed.
64 # @option options [String] :discovery_path ("/discovery/v1")
65 # The discovery base path. This rarely needs to be changed.
66 def initialize(options={})
67 # Normalize key to String to allow indifferent access.
68 options = options.inject({}) do |accu, (key, value)|
69 accu[key.to_s] = value
72 # Almost all API usage will have a host of 'www.googleapis.com'.
73 self.host = options["host"] || 'www.googleapis.com'
74 self.port = options["port"] || 443
75 self.discovery_path = options["discovery_path"] || '/discovery/v1'
77 # Most developers will want to leave this value alone and use the
78 # application_name option.
79 application_string = (
80 options["application_name"] ? (
81 "#{options["application_name"]}/" +
82 "#{options["application_version"] || '0.0.0'}"
85 self.user_agent = options["user_agent"] || (
86 "#{application_string} " +
87 "google-api-ruby-client/#{VERSION::STRING} " +
90 # The writer method understands a few Symbols and will generate useful
91 # default authentication mechanisms.
93 options.key?("authorization") ? options["authorization"] : :oauth_2
94 self.key = options["key"]
95 self.user_ip = options["user_ip"]
97 @discovery_documents = {}
103 # Returns the authorization mechanism used by the client.
105 # @return [#generate_authenticated_request] The authorization mechanism.
106 attr_reader :authorization
109 # Sets the authorization mechanism used by the client.
111 # @param [#generate_authenticated_request] new_authorization
112 # The new authorization mechanism.
113 def authorization=(new_authorization)
114 case new_authorization
115 when :oauth_1, :oauth
116 gem 'signet', '~> 0.4.0'
117 require 'signet/oauth_1/client'
118 # NOTE: Do not rely on this default value, as it may change
119 new_authorization = Signet::OAuth1::Client.new(
120 :temporary_credential_uri =>
121 'https://www.google.com/accounts/OAuthGetRequestToken',
122 :authorization_uri =>
123 'https://www.google.com/accounts/OAuthAuthorizeToken',
124 :token_credential_uri =>
125 'https://www.google.com/accounts/OAuthGetAccessToken',
126 :client_credential_key => 'anonymous',
127 :client_credential_secret => 'anonymous'
129 when :two_legged_oauth_1, :two_legged_oauth
130 gem 'signet', '~> 0.4.0'
131 require 'signet/oauth_1/client'
132 # NOTE: Do not rely on this default value, as it may change
133 new_authorization = Signet::OAuth1::Client.new(
134 :client_credential_key => nil,
135 :client_credential_secret => nil,
139 gem 'signet', '~> 0.4.0'
140 require 'signet/oauth_2/client'
141 # NOTE: Do not rely on this default value, as it may change
142 new_authorization = Signet::OAuth2::Client.new(
143 :authorization_uri =>
144 'https://accounts.google.com/o/oauth2/auth',
145 :token_credential_uri =>
146 'https://accounts.google.com/o/oauth2/token'
149 # No authorization mechanism
151 if !new_authorization.respond_to?(:generate_authenticated_request)
153 'Expected authorization mechanism to respond to ' +
154 '#generate_authenticated_request.'
157 @authorization = new_authorization
158 return @authorization
162 # The application's API key issued by the API console.
164 # @return [String] The API key.
168 # The IP address of the user this request is being performed on behalf of.
170 # @return [String] The user's IP address.
171 attr_accessor :user_ip
174 # The user agent used by the client.
177 # The user agent string used in the User-Agent header.
178 attr_accessor :user_agent
181 # The API hostname used by the client.
184 # The API hostname. Should almost always be 'www.googleapis.com'.
188 # The port number used by the client.
191 # The port number. Should almost always be 443.
195 # The base path used by the client for discovery.
198 # The base path. Should almost always be '/discovery/v1'.
199 attr_accessor :discovery_path
202 # Resolves a URI template against the client's configured base.
204 # @param [String, Addressable::URI, Addressable::Template] template
205 # The template to resolve.
206 # @param [Hash] mapping The mapping that corresponds to the template.
207 # @return [Addressable::URI] The expanded URI.
208 def resolve_uri(template, mapping={})
209 @base_uri ||= Addressable::URI.new(
214 template = if template.kind_of?(Addressable::Template)
216 elsif template.respond_to?(:to_str)
220 "Expected String, Addressable::URI, or Addressable::Template, " +
221 "got #{template.class}."
223 return Addressable::Template.new(@base_uri + template).expand(mapping)
227 # Returns the URI for the directory document.
229 # @return [Addressable::URI] The URI of the directory document.
231 return resolve_uri(self.discovery_path + '/apis')
235 # Manually registers a URI as a 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 [Addressable::URI] uri The URI of the discovery document.
241 def register_discovery_uri(api, version, uri)
243 version = version || 'v1'
244 @discovery_uris["#{api}:#{version}"] = uri
248 # Returns the URI for the discovery document.
250 # @param [String, Symbol] api The API name.
251 # @param [String] version The desired version of the API.
252 # @return [Addressable::URI] The URI of the discovery document.
253 def discovery_uri(api, version=nil)
255 version = version || 'v1'
256 return @discovery_uris["#{api}:#{version}"] ||= (
258 self.discovery_path + '/apis/{api}/{version}/rest',
266 # Manually registers a pre-loaded discovery document for a specific version
269 # @param [String, Symbol] api The API name.
270 # @param [String] version The desired version of the API.
271 # @param [String, StringIO] discovery_document
272 # The contents of the discovery document.
273 def register_discovery_document(api, version, discovery_document)
275 version = version || 'v1'
276 if discovery_document.kind_of?(StringIO)
277 discovery_document.rewind
278 discovery_document = discovery_document.string
279 elsif discovery_document.respond_to?(:to_str)
280 discovery_document = discovery_document.to_str
283 "Expected String or StringIO, got #{discovery_document.class}."
285 @discovery_documents["#{api}:#{version}"] =
286 MultiJson.load(discovery_document)
290 # Returns the parsed directory document.
292 # @return [Hash] The parsed JSON from the directory document.
293 def directory_document
294 return @directory_document ||= (begin
295 request = self.generate_request(
296 :http_method => :get,
297 :uri => self.directory_uri,
298 :authenticated => false
300 response = self.transmit(:request => request)
301 if response.status >= 200 && response.status < 300
302 MultiJson.load(response.body)
303 elsif response.status >= 400
306 exception_type = ClientError
308 exception_type = ServerError
310 exception_type = TransmissionError
312 url = request.to_env(Faraday.default_connection)[:url]
313 raise exception_type,
314 "Could not retrieve directory document at: #{url}"
320 # Returns the parsed discovery document.
322 # @param [String, Symbol] api The API name.
323 # @param [String] version The desired version of the API.
324 # @return [Hash] The parsed JSON from the discovery document.
325 def discovery_document(api, version=nil)
327 version = version || 'v1'
328 return @discovery_documents["#{api}:#{version}"] ||= (begin
329 request = self.generate_request(
330 :http_method => :get,
331 :uri => self.discovery_uri(api, version),
332 :authenticated => false
334 response = self.transmit(:request => request)
335 if response.status >= 200 && response.status < 300
336 MultiJson.load(response.body)
337 elsif response.status >= 400
340 exception_type = ClientError
342 exception_type = ServerError
344 exception_type = TransmissionError
346 url = request.to_env(Faraday.default_connection)[:url]
347 raise exception_type,
348 "Could not retrieve discovery document at: #{url}"
354 # Returns all APIs published in the directory document.
356 # @return [Array] The list of available APIs.
358 @directory_apis ||= (begin
359 document_base = self.directory_uri
360 if self.directory_document && self.directory_document['items']
361 self.directory_document['items'].map do |discovery_document|
362 Google::APIClient::API.new(
374 # Returns the service object for a given service name and service version.
376 # @param [String, Symbol] api The API name.
377 # @param [String] version The desired version of the API.
379 # @return [Google::APIClient::API] The service object.
380 def discovered_api(api, version=nil)
381 if !api.kind_of?(String) && !api.kind_of?(Symbol)
383 "Expected String or Symbol, got #{api.class}."
386 version = version || 'v1'
387 return @discovered_apis["#{api}:#{version}"] ||= begin
388 document_base = self.discovery_uri(api, version)
389 discovery_document = self.discovery_document(api, version)
390 if document_base && discovery_document
391 Google::APIClient::API.new(
402 # Returns the method object for a given RPC name and service version.
404 # @param [String, Symbol] rpc_name The RPC name of the desired method.
405 # @param [String, Symbol] rpc_name The API the method is within.
406 # @param [String] version The desired version of the API.
408 # @return [Google::APIClient::Method] The method object.
409 def discovered_method(rpc_name, api, version=nil)
410 if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
412 "Expected String or Symbol, got #{rpc_name.class}."
414 rpc_name = rpc_name.to_s
416 version = version || 'v1'
417 service = self.discovered_api(api, version)
418 if service.to_h[rpc_name]
419 return service.to_h[rpc_name]
426 # Returns the service object with the highest version number.
428 # @note <em>Warning</em>: This method should be used with great care.
429 # As APIs are updated, minor differences between versions may cause
430 # incompatibilities. Requesting a specific version will avoid this issue.
432 # @param [String, Symbol] api The name of the service.
434 # @return [Google::APIClient::API] The service object.
435 def preferred_version(api)
436 if !api.kind_of?(String) && !api.kind_of?(Symbol)
438 "Expected String or Symbol, got #{api.class}."
441 return self.discovered_apis.detect do |a|
442 a.name == api && a.preferred == true
447 # Verifies an ID token against a server certificate. Used to ensure that
448 # an ID token supplied by an untrusted client-side mechanism is valid.
449 # Raises an error if the token is invalid or missing.
451 gem 'jwt', '~> 0.1.4'
455 if !self.authorization.respond_to?(:id_token)
456 raise ArgumentError, (
457 "Current authorization mechanism does not support ID tokens: " +
458 "#{self.authorization.class.to_s}"
460 elsif !self.authorization.id_token
461 raise ArgumentError, (
462 "Could not verify ID token, ID token missing. " +
463 "Scopes were: #{self.authorization.scope.inspect}"
466 check_cached_certs = lambda do
468 for key, cert in @certificates
470 self.authorization.decoded_id_token(cert.public_key)
472 rescue JWT::DecodeError, Signet::UnsafeOperationError
473 # Expected exception. Ignore, ID token has not been validated.
478 if check_cached_certs.call()
481 request = self.generate_request(
482 :http_method => :get,
483 :uri => 'https://www.googleapis.com/oauth2/v1/certs',
484 :authenticated => false
486 response = self.transmit(:request => request)
487 if response.status >= 200 && response.status < 300
488 @certificates.merge!(
489 Hash[MultiJson.load(response.body).map do |key, cert|
490 [key, OpenSSL::X509::Certificate.new(cert)]
493 elsif response.status >= 400
496 exception_type = ClientError
498 exception_type = ServerError
500 exception_type = TransmissionError
502 url = request.to_env(Faraday.default_connection)[:url]
503 raise exception_type,
504 "Could not retrieve certificates from: #{url}"
506 if check_cached_certs.call()
509 raise InvalidIDTokenError,
510 "Could not verify ID token against any available certificate."
517 # Generates a request.
519 # @option options [Google::APIClient::Method, String] :api_method
520 # The method object or the RPC name of the method being executed.
521 # @option options [Hash, Array] :parameters
522 # The parameters to send to the method.
523 # @option options [Hash, Array] :headers The HTTP headers for the request.
524 # @option options [String] :body The body of the request.
525 # @option options [String] :version ("v1")
526 # The service version. Only used if `api_method` is a `String`.
527 # @option options [#generate_authenticated_request] :authorization
528 # The authorization mechanism for the response. Used only if
529 # `:authenticated` is `true`.
530 # @option options [TrueClass, FalseClass] :authenticated (true)
531 # `true` if the request must be signed or somehow
532 # authenticated, `false` otherwise.
534 # @return [Faraday::Request] The generated request.
537 # request = client.generate_request(
538 # :api_method => 'plus.activities.list',
540 # {'collection' => 'public', 'userId' => 'me'}
542 def generate_request(options={})
543 # Note: The merge method on a Hash object will coerce an API Reference
544 # object into a Hash and merge with the default options.
548 :authorization => self.authorization,
550 :user_ip => self.user_ip,
551 :connection => Faraday.default_connection
554 # The Reference object is going to need this to do method ID lookups.
555 options[:client] = self
556 # The default value for the :authenticated option depends on whether an
557 # authorization mechanism has been set.
558 if options[:authorization]
559 options = {:authenticated => true}.merge(options)
561 options = {:authenticated => false}.merge(options)
563 reference = Google::APIClient::Reference.new(options)
564 request = reference.to_request
565 if options[:authenticated]
566 request = options[:authorization].generate_authenticated_request(
568 :connection => options[:connection]
575 # Signs a request using the current authorization mechanism.
577 # @param [Hash] options a customizable set of options
579 # @return [Faraday::Request] The signed or otherwise authenticated request.
580 # @deprecated No longer used internally
581 def generate_authenticated_request(options={})
582 return authorization.generate_authenticated_request(options)
586 # Transmits the request using the current HTTP adapter.
588 # @option options [Array, Faraday::Request] :request
589 # The HTTP request to transmit.
590 # @option options [String, Symbol] :method
591 # The method for the HTTP request.
592 # @option options [String, Addressable::URI] :uri
593 # The URI for the HTTP request.
594 # @option options [Array, Hash] :headers
595 # The headers for the HTTP request.
596 # @option options [String] :body
597 # The body for the HTTP request.
598 # @option options [Faraday::Connection] :connection
599 # The HTTP connection to use.
601 # @return [Faraday::Response] The response from the server.
602 def transmit(options={})
603 options[:connection] ||= Faraday.default_connection
605 if options[:request].kind_of?(Array)
606 method, uri, headers, body = options[:request]
607 elsif options[:request].kind_of?(Faraday::Request)
608 unless options[:connection]
610 "Faraday::Request used, requires a connection to be provided."
612 method = options[:request].method.to_s.downcase.to_sym
613 uri = options[:connection].build_url(
614 options[:request].path, options[:request].params
616 headers = options[:request].headers || {}
617 body = options[:request].body || ''
620 method = options[:method] || :get
622 headers = options[:headers] || []
623 body = options[:body] || ''
625 headers = headers.to_a if headers.kind_of?(Hash)
626 request_components = {
632 # Verify that we have all pieces required to transmit an HTTP request
633 request_components.each do |(key, value)|
635 raise ArgumentError, "Missing :#{key} parameter."
639 if self.user_agent != nil
640 # If there's no User-Agent header, set one.
641 unless headers.kind_of?(Enumerable)
642 # We need to use some Enumerable methods, relying on the presence of
648 if self.user_agent.kind_of?(String)
649 unless headers.any? { |k, v| k.downcase == 'User-Agent'.downcase }
650 headers = headers.to_a.insert(0, ['User-Agent', self.user_agent])
652 elsif self.user_agent != nil
654 "Expected User-Agent to be String, got #{self.user_agent.class}"
658 request = options[:connection].build_request(
659 method.to_s.downcase.to_sym
661 req.url(Addressable::URI.parse(uri).normalize.to_s)
662 req.headers = Faraday::Utils::Headers.new(headers)
665 request_env = request.to_env(options[:connection])
666 response = options[:connection].app.call(request_env)
671 # Executes a request, wrapping it in a Result object.
673 # @param [Google::APIClient::BatchRequest, Hash, Array] params
674 # Either a Google::APIClient::BatchRequest, a Hash, or an Array.
676 # If a Google::APIClient::BatchRequest, no other parameters are expected.
678 # If a Hash, the below parameters are handled. If an Array, the
679 # parameters are assumed to be in the below order:
681 # - (Google::APIClient::Method, String) api_method:
682 # The method object or the RPC name of the method being executed.
683 # - (Hash, Array) parameters:
684 # The parameters to send to the method.
685 # - (String) body: The body of the request.
686 # - (Hash, Array) headers: The HTTP headers for the request.
687 # - (Hash) options: A set of options for the request, of which:
688 # - (String) :version (default: "v1") -
689 # The service version. Only used if `api_method` is a `String`.
690 # - (#generate_authenticated_request) :authorization (default: true) -
691 # The authorization mechanism for the response. Used only if
692 # `:authenticated` is `true`.
693 # - (TrueClass, FalseClass) :authenticated (default: true) -
694 # `true` if the request must be signed or somehow
695 # authenticated, `false` otherwise.
697 # @return [Google::APIClient::Result] The result from the API, nil if batch.
700 # result = client.execute(batch_request)
703 # result = client.execute(
704 # :api_method => 'plus.activities.list',
705 # :parameters => {'collection' => 'public', 'userId' => 'me'}
708 # @see Google::APIClient#generate_request
710 if params.last.kind_of?(Google::APIClient::BatchRequest) &&
713 options = batch.options
714 options[:connection] ||= Faraday.default_connection
715 http_request = batch.to_http_request
719 method, uri, headers, body = http_request
720 method = method.to_s.downcase.to_sym
722 faraday_request = options[:connection].build_request(
723 method.to_s.downcase.to_sym
725 req.url(Addressable::URI.parse(uri).normalize.to_s)
726 req.headers = Faraday::Utils::Headers.new(headers)
731 :request => self.generate_authenticated_request(
732 :request => faraday_request,
733 :connection => options[:connection]
735 :connection => options[:connection]
739 :request => http_request,
740 :connection => options[:connection]
744 response = self.transmit(request)
745 batch.process_response(response)
748 # This block of code allows us to accept multiple parameter passing
749 # styles, and maintaining some backwards compatibility.
751 # Note: I'm extremely tempted to deprecate this style of execute call.
752 if params.last.respond_to?(:to_hash) && params.size == 1
758 options[:api_method] = params.shift if params.size > 0
759 options[:parameters] = params.shift if params.size > 0
760 options[:body] = params.shift if params.size > 0
761 options[:headers] = params.shift if params.size > 0
762 options[:client] = self
763 options[:connection] ||= Faraday.default_connection
764 reference = Google::APIClient::Reference.new(options)
765 request = self.generate_request(reference)
766 response = self.transmit(
768 :connection => options[:connection]
770 return Google::APIClient::Result.new(reference, request, response)
775 # Same as Google::APIClient#execute, but raises an exception if there was
778 # @see Google::APIClient#execute
779 def execute!(*params)
780 result = self.execute(*params)
782 if result.data.respond_to?(:error) &&
783 result.data.error.respond_to?(:message)
784 # You're going to get a terrible error message if the response isn't
785 # parsed successfully as an error.
786 error_message = result.data.error.message
787 elsif result.data['error'] && result.data['error']['message']
788 error_message = result.data['error']['message']
791 if result.response.status >= 400
792 case result.response.status
794 exception_type = ClientError
795 error_message ||= "A client error has occurred."
797 exception_type = ServerError
798 error_message ||= "A server error has occurred."
800 exception_type = TransmissionError
801 error_message ||= "A transmission error has occurred."
803 raise exception_type, error_message
810 require 'google/api_client/version'