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.7.0'
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'
31 # TODO(bobaman): Document all this stuff.
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] :host ("www.googleapis.com")
51 # The API hostname used by the client. This rarely needs to be changed.
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 def initialize(options={})
61 # Normalize key to String to allow indifferent access.
62 options = options.inject({}) do |accu, (key, value)|
63 accu[key.to_s] = value
66 # Almost all API usage will have a host of 'www.googleapis.com'.
67 self.host = options["host"] || 'www.googleapis.com'
68 # Most developers will want to leave this value alone and use the
69 # application_name option.
70 application_string = (
71 options["application_name"] ? (
72 "#{options["application_name"]}/" +
73 "#{options["application_version"] || '0.0.0'}"
76 self.user_agent = options["user_agent"] || (
77 "#{application_string} " +
78 "google-api-ruby-client/#{VERSION::STRING} " +
81 # The writer method understands a few Symbols and will generate useful
82 # default authentication mechanisms.
83 self.authorization = options["authorization"] || :oauth_2
84 self.key = options["key"]
85 self.user_ip = options["user_ip"]
87 @discovery_documents = {}
93 # Returns the authorization mechanism used by the client.
95 # @return [#generate_authenticated_request] The authorization mechanism.
96 attr_reader :authorization
99 # Sets the authorization mechanism used by the client.
101 # @param [#generate_authenticated_request] new_authorization
102 # The new authorization mechanism.
103 def authorization=(new_authorization)
104 case new_authorization
105 when :oauth_1, :oauth
106 gem 'signet', '~> 0.3.0'
107 require 'signet/oauth_1/client'
108 # NOTE: Do not rely on this default value, as it may change
109 new_authorization = Signet::OAuth1::Client.new(
110 :temporary_credential_uri =>
111 'https://www.google.com/accounts/OAuthGetRequestToken',
112 :authorization_uri =>
113 'https://www.google.com/accounts/OAuthAuthorizeToken',
114 :token_credential_uri =>
115 'https://www.google.com/accounts/OAuthGetAccessToken',
116 :client_credential_key => 'anonymous',
117 :client_credential_secret => 'anonymous'
119 when :two_legged_oauth_1, :two_legged_oauth
120 gem 'signet', '~> 0.3.0'
121 require 'signet/oauth_1/client'
122 # NOTE: Do not rely on this default value, as it may change
123 new_authorization = Signet::OAuth1::Client.new(
124 :client_credential_key => nil,
125 :client_credential_secret => nil,
129 gem 'signet', '~> 0.3.0'
130 require 'signet/oauth_2/client'
131 # NOTE: Do not rely on this default value, as it may change
132 new_authorization = Signet::OAuth2::Client.new(
133 :authorization_uri =>
134 'https://accounts.google.com/o/oauth2/auth',
135 :token_credential_uri =>
136 'https://accounts.google.com/o/oauth2/token'
139 # No authorization mechanism
141 if !new_authorization.respond_to?(:generate_authenticated_request)
143 'Expected authorization mechanism to respond to ' +
144 '#generate_authenticated_request.'
147 @authorization = new_authorization
148 return @authorization
152 # The application's API key issued by the API console.
154 # @return [String] The API key.
158 # The IP address of the user this request is being performed on behalf of.
160 # @return [String] The user's IP address.
161 attr_accessor :user_ip
164 # The API hostname used by the client.
167 # The API hostname. Should almost always be 'www.googleapis.com'.
171 # The user agent used by the client.
174 # The user agent string used in the User-Agent header.
175 attr_accessor :user_agent
178 # Returns the URI for the directory document.
180 # @return [Addressable::URI] The URI of the directory document.
182 template = Addressable::Template.new(
183 "https://{host}/discovery/v1/apis"
185 return template.expand({"host" => self.host})
189 # Manually registers a URI as a discovery document for a specific version
192 # @param [String, Symbol] api The API name.
193 # @param [String] version The desired version of the API.
194 # @param [Addressable::URI] uri The URI of the discovery document.
195 def register_discovery_uri(api, version, uri)
197 version = version || 'v1'
198 @discovery_uris["#{api}:#{version}"] = uri
202 # Returns the URI for the discovery document.
204 # @param [String, Symbol] api The API name.
205 # @param [String] version The desired version of the API.
206 # @return [Addressable::URI] The URI of the discovery document.
207 def discovery_uri(api, version=nil)
209 version = version || 'v1'
210 return @discovery_uris["#{api}:#{version}"] ||= (begin
211 template = Addressable::Template.new(
212 "https://{host}/discovery/v1/apis/" +
213 "{api}/{version}/rest"
224 # Manually registers a pre-loaded discovery document for a specific version
227 # @param [String, Symbol] api The API name.
228 # @param [String] version The desired version of the API.
229 # @param [String, StringIO] discovery_document
230 # The contents of the discovery document.
231 def register_discovery_document(api, version, discovery_document)
233 version = version || 'v1'
234 if discovery_document.kind_of?(StringIO)
235 discovery_document.rewind
236 discovery_document = discovery_document.string
237 elsif discovery_document.respond_to?(:to_str)
238 discovery_document = discovery_document.to_str
241 "Expected String or StringIO, got #{discovery_document.class}."
243 @discovery_documents["#{api}:#{version}"] =
244 MultiJson.decode(discovery_document)
248 # Returns the parsed directory document.
250 # @return [Hash] The parsed JSON from the directory document.
251 def directory_document
252 return @directory_document ||= (begin
253 request = self.generate_request(
254 :http_method => :get,
255 :uri => self.directory_uri,
256 :authenticated => false
258 response = self.transmit(:request => request)
259 if response.status >= 200 && response.status < 300
260 MultiJson.decode(response.body)
261 elsif response.status >= 400
264 exception_type = ClientError
266 exception_type = ServerError
268 exception_type = TransmissionError
270 url = request.to_env(Faraday.default_connection)[:url]
271 raise exception_type,
272 "Could not retrieve directory document at: #{url}"
278 # Returns the parsed discovery document.
280 # @param [String, Symbol] api The API name.
281 # @param [String] version The desired version of the API.
282 # @return [Hash] The parsed JSON from the discovery document.
283 def discovery_document(api, version=nil)
285 version = version || 'v1'
286 return @discovery_documents["#{api}:#{version}"] ||= (begin
287 request = self.generate_request(
288 :http_method => :get,
289 :uri => self.discovery_uri(api, version),
290 :authenticated => false
292 response = self.transmit(:request => request)
293 if response.status >= 200 && response.status < 300
294 MultiJson.decode(response.body)
295 elsif response.status >= 400
298 exception_type = ClientError
300 exception_type = ServerError
302 exception_type = TransmissionError
304 url = request.to_env(Faraday.default_connection)[:url]
305 raise exception_type,
306 "Could not retrieve discovery document at: #{url}"
312 # Returns all APIs published in the directory document.
314 # @return [Array] The list of available APIs.
316 @directory_apis ||= (begin
317 document_base = self.directory_uri
318 if self.directory_document && self.directory_document['items']
319 self.directory_document['items'].map do |discovery_document|
320 Google::APIClient::API.new(
332 # Returns the service object for a given service name and service version.
334 # @param [String, Symbol] api The API name.
335 # @param [String] version The desired version of the API.
337 # @return [Google::APIClient::API] The service object.
338 def discovered_api(api, version=nil)
339 if !api.kind_of?(String) && !api.kind_of?(Symbol)
341 "Expected String or Symbol, got #{api.class}."
344 version = version || 'v1'
345 return @discovered_apis["#{api}:#{version}"] ||= begin
346 document_base = self.discovery_uri(api, version)
347 discovery_document = self.discovery_document(api, version)
348 if document_base && discovery_document
349 Google::APIClient::API.new(
360 # Returns the method object for a given RPC name and service version.
362 # @param [String, Symbol] rpc_name The RPC name of the desired method.
363 # @param [String, Symbol] rpc_name The API the method is within.
364 # @param [String] version The desired version of the API.
366 # @return [Google::APIClient::Method] The method object.
367 def discovered_method(rpc_name, api, version=nil)
368 if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
370 "Expected String or Symbol, got #{rpc_name.class}."
372 rpc_name = rpc_name.to_s
374 version = version || 'v1'
375 service = self.discovered_api(api, version)
376 if service.to_h[rpc_name]
377 return service.to_h[rpc_name]
384 # Returns the service object with the highest version number.
386 # @note <em>Warning</em>: This method should be used with great care.
387 # As APIs are updated, minor differences between versions may cause
388 # incompatibilities. Requesting a specific version will avoid this issue.
390 # @param [String, Symbol] api The name of the service.
392 # @return [Google::APIClient::API] The service object.
393 def preferred_version(api)
394 if !api.kind_of?(String) && !api.kind_of?(Symbol)
396 "Expected String or Symbol, got #{api.class}."
399 return self.discovered_apis.detect do |a|
400 a.name == api && a.preferred == true
405 # Verifies an ID token against a server certificate. Used to ensure that
406 # an ID token supplied by an untrusted client-side mechanism is valid.
407 # Raises an error if the token is invalid or missing.
409 gem 'jwt', '~> 0.1.4'
413 if !self.authorization.respond_to?(:id_token)
414 raise ArgumentError, (
415 "Current authorization mechanism does not support ID tokens: " +
416 "#{self.authorization.class.to_s}"
418 elsif !self.authorization.id_token
419 raise ArgumentError, (
420 "Could not verify ID token, ID token missing. " +
421 "Scopes were: #{self.authorization.scope.inspect}"
424 check_cached_certs = lambda do
426 for key, cert in @certificates
428 self.authorization.decoded_id_token(cert.public_key)
430 rescue JWT::DecodeError, Signet::UnsafeOperationError
431 # Expected exception. Ignore, ID token has not been validated.
436 if check_cached_certs.call()
439 request = self.generate_request(
440 :http_method => :get,
441 :uri => 'https://www.googleapis.com/oauth2/v1/certs',
442 :authenticated => false
444 response = self.transmit(:request => request)
445 if response.status >= 200 && response.status < 300
446 @certificates.merge!(
447 Hash[MultiJson.decode(response.body).map do |key, cert|
448 [key, OpenSSL::X509::Certificate.new(cert)]
451 elsif response.status >= 400
454 exception_type = ClientError
456 exception_type = ServerError
458 exception_type = TransmissionError
460 url = request.to_env(Faraday.default_connection)[:url]
461 raise exception_type,
462 "Could not retrieve certificates from: #{url}"
464 if check_cached_certs.call()
467 raise InvalidIDTokenError,
468 "Could not verify ID token against any available certificate."
475 # Generates a request.
477 # @option options [Google::APIClient::Method, String] :api_method
478 # The method object or the RPC name of the method being executed.
479 # @option options [Hash, Array] :parameters
480 # The parameters to send to the method.
481 # @option options [Hash, Array] :headers The HTTP headers for the request.
482 # @option options [String] :body The body of the request.
483 # @option options [String] :version ("v1")
484 # The service version. Only used if `api_method` is a `String`.
485 # @option options [#generate_authenticated_request] :authorization
486 # The authorization mechanism for the response. Used only if
487 # `:authenticated` is `true`.
488 # @option options [TrueClass, FalseClass] :authenticated (true)
489 # `true` if the request must be signed or somehow
490 # authenticated, `false` otherwise.
492 # @return [Faraday::Request] The generated request.
495 # request = client.generate_request(
496 # :api_method => 'plus.activities.list',
498 # {'collection' => 'public', 'userId' => 'me'}
500 def generate_request(options={})
501 # Note: The merge method on a Hash object will coerce an API Reference
502 # object into a Hash and merge with the default options.
505 :authorization => self.authorization,
507 :user_ip => self.user_ip,
508 :connection => Faraday.default_connection
510 # The Reference object is going to need this to do method ID lookups.
511 options[:client] = self
512 # The default value for the :authenticated option depends on whether an
513 # authorization mechanism has been set.
514 if options[:authorization]
515 options = {:authenticated => true}.merge(options)
517 options = {:authenticated => false}.merge(options)
519 reference = Google::APIClient::Reference.new(options)
520 request = reference.to_request
521 if options[:authenticated]
522 request = self.generate_authenticated_request(
524 :connection => options[:connection]
531 # Signs a request using the current authorization mechanism.
533 # @param [Hash] options a customizable set of options
535 # @return [Faraday::Request] The signed or otherwise authenticated request.
536 def generate_authenticated_request(options={})
537 return authorization.generate_authenticated_request(options)
541 # Transmits the request using the current HTTP adapter.
543 # @option options [Array, Faraday::Request] :request
544 # The HTTP request to transmit.
545 # @option options [String, Symbol] :method
546 # The method for the HTTP request.
547 # @option options [String, Addressable::URI] :uri
548 # The URI for the HTTP request.
549 # @option options [Array, Hash] :headers
550 # The headers for the HTTP request.
551 # @option options [String] :body
552 # The body for the HTTP request.
553 # @option options [Faraday::Connection] :connection
554 # The HTTP connection to use.
556 # @return [Faraday::Response] The response from the server.
557 def transmit(options={})
558 options[:connection] ||= Faraday.default_connection
560 if options[:request].kind_of?(Array)
561 method, uri, headers, body = options[:request]
562 elsif options[:request].kind_of?(Faraday::Request)
563 unless options[:connection]
565 "Faraday::Request used, requires a connection to be provided."
567 method = options[:request].method.to_s.downcase.to_sym
568 uri = options[:connection].build_url(
569 options[:request].path, options[:request].params
571 headers = options[:request].headers || {}
572 body = options[:request].body || ''
575 method = options[:method] || :get
577 headers = options[:headers] || []
578 body = options[:body] || ''
580 headers = headers.to_a if headers.kind_of?(Hash)
581 request_components = {
587 # Verify that we have all pieces required to transmit an HTTP request
588 request_components.each do |(key, value)|
590 raise ArgumentError, "Missing :#{key} parameter."
594 if self.user_agent != nil
595 # If there's no User-Agent header, set one.
596 unless headers.kind_of?(Enumerable)
597 # We need to use some Enumerable methods, relying on the presence of
603 if self.user_agent.kind_of?(String)
604 unless headers.any? { |k, v| k.downcase == 'User-Agent'.downcase }
605 headers = headers.to_a.insert(0, ['User-Agent', self.user_agent])
607 elsif self.user_agent != nil
609 "Expected User-Agent to be String, got #{self.user_agent.class}"
613 request = Faraday::Request.create(method.to_s.downcase.to_sym) do |req|
614 req.url(Addressable::URI.parse(uri))
615 req.headers = Faraday::Utils::Headers.new(headers)
618 request_env = request.to_env(options[:connection])
619 response = options[:connection].app.call(request_env)
624 # Executes a request, wrapping it in a Result object.
626 # @param [Google::APIClient::Method, String] api_method
627 # The method object or the RPC name of the method being executed.
628 # @param [Hash, Array] parameters
629 # The parameters to send to the method.
630 # @param [String] body The body of the request.
631 # @param [Hash, Array] headers The HTTP headers for the request.
632 # @option options [String] :version ("v1")
633 # The service version. Only used if `api_method` is a `String`.
634 # @option options [#generate_authenticated_request] :authorization
635 # The authorization mechanism for the response. Used only if
636 # `:authenticated` is `true`.
637 # @option options [TrueClass, FalseClass] :authenticated (true)
638 # `true` if the request must be signed or somehow
639 # authenticated, `false` otherwise.
641 # @return [Google::APIClient::Result] The result from the API.
644 # result = client.execute(
645 # :api_method => 'plus.activities.list',
646 # :parameters => {'collection' => 'public', 'userId' => 'me'}
649 # @see Google::APIClient#generate_request
651 # This block of code allows us to accept multiple parameter passing
652 # styles, and maintaining some backwards compatibility.
654 # Note: I'm extremely tempted to deprecate this style of execute call.
655 if params.last.respond_to?(:to_hash) && params.size == 1
660 options[:api_method] = params.shift if params.size > 0
661 options[:parameters] = params.shift if params.size > 0
662 options[:body] = params.shift if params.size > 0
663 options[:headers] = params.shift if params.size > 0
664 options[:client] = self
666 reference = Google::APIClient::Reference.new(options)
667 request = self.generate_request(reference)
668 response = self.transmit(
670 :connection => options[:connection]
672 return Google::APIClient::Result.new(reference, request, response)
676 # Same as Google::APIClient#execute, but raises an exception if there was
679 # @see Google::APIClient#execute
680 def execute!(*params)
681 result = self.execute(*params)
682 if result.data.respond_to?(:error) &&
683 result.data.error.respond_to?(:message)
684 # You're going to get a terrible error message if the response isn't
685 # parsed successfully as an error.
686 error_message = result.data.error.message
687 elsif result.data['error'] && result.data['error']['message']
688 error_message = result.data['error']['message']
690 if result.response.status >= 400
691 case result.response.status
693 exception_type = ClientError
694 error_message ||= "A client error has occurred."
696 exception_type = ServerError
697 error_message ||= "A server error has occurred."
699 exception_type = TransmissionError
700 error_message ||= "A transmission error has occurred."
702 raise exception_type, error_message
709 require 'google/api_client/version'