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'
28 require 'google/api_client/media'
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] :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_s] = 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 gem 'signet', '~> 0.3.0'
115 require 'signet/oauth_1/client'
116 # NOTE: Do not rely on this default value, as it may change
117 new_authorization = Signet::OAuth1::Client.new(
118 :temporary_credential_uri =>
119 'https://www.google.com/accounts/OAuthGetRequestToken',
120 :authorization_uri =>
121 'https://www.google.com/accounts/OAuthAuthorizeToken',
122 :token_credential_uri =>
123 'https://www.google.com/accounts/OAuthGetAccessToken',
124 :client_credential_key => 'anonymous',
125 :client_credential_secret => 'anonymous'
127 when :two_legged_oauth_1, :two_legged_oauth
128 gem 'signet', '~> 0.3.0'
129 require 'signet/oauth_1/client'
130 # NOTE: Do not rely on this default value, as it may change
131 new_authorization = Signet::OAuth1::Client.new(
132 :client_credential_key => nil,
133 :client_credential_secret => nil,
137 gem 'signet', '~> 0.3.0'
138 require 'signet/oauth_2/client'
139 # NOTE: Do not rely on this default value, as it may change
140 new_authorization = Signet::OAuth2::Client.new(
141 :authorization_uri =>
142 'https://accounts.google.com/o/oauth2/auth',
143 :token_credential_uri =>
144 'https://accounts.google.com/o/oauth2/token'
147 # No authorization mechanism
149 if !new_authorization.respond_to?(:generate_authenticated_request)
151 'Expected authorization mechanism to respond to ' +
152 '#generate_authenticated_request.'
155 @authorization = new_authorization
156 return @authorization
160 # The application's API key issued by the API console.
162 # @return [String] The API key.
166 # The IP address of the user this request is being performed on behalf of.
168 # @return [String] The user's IP address.
169 attr_accessor :user_ip
172 # The user agent used by the client.
175 # The user agent string used in the User-Agent header.
176 attr_accessor :user_agent
179 # The API hostname used by the client.
182 # The API hostname. Should almost always be 'www.googleapis.com'.
186 # The port number used by the client.
189 # The port number. Should almost always be 443.
193 # The base path used by the client for discovery.
196 # The base path. Should almost always be '/discovery/v1'.
197 attr_accessor :discovery_path
200 # Resolves a URI template against the client's configured base.
202 # @param [String, Addressable::URI, Addressable::Template] template
203 # The template to resolve.
204 # @param [Hash] mapping The mapping that corresponds to the template.
205 # @return [Addressable::URI] The expanded URI.
206 def resolve_uri(template, mapping={})
207 @base_uri ||= Addressable::URI.new(
212 template = if template.kind_of?(Addressable::Template)
214 elsif template.respond_to?(:to_str)
218 "Expected String, Addressable::URI, or Addressable::Template, " +
219 "got #{template.class}."
221 return Addressable::Template.new(@base_uri + template).expand(mapping)
225 # Returns the URI for the directory document.
227 # @return [Addressable::URI] The URI of the directory document.
229 return resolve_uri(self.discovery_path + '/apis')
233 # Manually registers a URI as a discovery document for a specific version
236 # @param [String, Symbol] api The API name.
237 # @param [String] version The desired version of the API.
238 # @param [Addressable::URI] uri The URI of the discovery document.
239 def register_discovery_uri(api, version, uri)
241 version = version || 'v1'
242 @discovery_uris["#{api}:#{version}"] = uri
246 # Returns the URI for the discovery document.
248 # @param [String, Symbol] api The API name.
249 # @param [String] version The desired version of the API.
250 # @return [Addressable::URI] The URI of the discovery document.
251 def discovery_uri(api, version=nil)
253 version = version || 'v1'
254 return @discovery_uris["#{api}:#{version}"] ||= (
256 self.discovery_path + '/apis/{api}/{version}/rest',
264 # Manually registers a pre-loaded discovery document for a specific version
267 # @param [String, Symbol] api The API name.
268 # @param [String] version The desired version of the API.
269 # @param [String, StringIO] discovery_document
270 # The contents of the discovery document.
271 def register_discovery_document(api, version, discovery_document)
273 version = version || 'v1'
274 if discovery_document.kind_of?(StringIO)
275 discovery_document.rewind
276 discovery_document = discovery_document.string
277 elsif discovery_document.respond_to?(:to_str)
278 discovery_document = discovery_document.to_str
281 "Expected String or StringIO, got #{discovery_document.class}."
283 @discovery_documents["#{api}:#{version}"] =
284 MultiJson.load(discovery_document)
288 # Returns the parsed directory document.
290 # @return [Hash] The parsed JSON from the directory document.
291 def directory_document
292 return @directory_document ||= (begin
293 request = self.generate_request(
294 :http_method => :get,
295 :uri => self.directory_uri,
296 :authenticated => false
298 response = self.transmit(:request => request)
299 if response.status >= 200 && response.status < 300
300 MultiJson.load(response.body)
301 elsif response.status >= 400
304 exception_type = ClientError
306 exception_type = ServerError
308 exception_type = TransmissionError
310 url = request.to_env(Faraday.default_connection)[:url]
311 raise exception_type,
312 "Could not retrieve directory document at: #{url}"
318 # Returns the parsed discovery document.
320 # @param [String, Symbol] api The API name.
321 # @param [String] version The desired version of the API.
322 # @return [Hash] The parsed JSON from the discovery document.
323 def discovery_document(api, version=nil)
325 version = version || 'v1'
326 return @discovery_documents["#{api}:#{version}"] ||= (begin
327 request = self.generate_request(
328 :http_method => :get,
329 :uri => self.discovery_uri(api, version),
330 :authenticated => false
332 response = self.transmit(:request => request)
333 if response.status >= 200 && response.status < 300
334 MultiJson.load(response.body)
335 elsif response.status >= 400
338 exception_type = ClientError
340 exception_type = ServerError
342 exception_type = TransmissionError
344 url = request.to_env(Faraday.default_connection)[:url]
345 raise exception_type,
346 "Could not retrieve discovery document at: #{url}"
352 # Returns all APIs published in the directory document.
354 # @return [Array] The list of available APIs.
356 @directory_apis ||= (begin
357 document_base = self.directory_uri
358 if self.directory_document && self.directory_document['items']
359 self.directory_document['items'].map do |discovery_document|
360 Google::APIClient::API.new(
372 # Returns the service object for a given service name and service version.
374 # @param [String, Symbol] api The API name.
375 # @param [String] version The desired version of the API.
377 # @return [Google::APIClient::API] The service object.
378 def discovered_api(api, version=nil)
379 if !api.kind_of?(String) && !api.kind_of?(Symbol)
381 "Expected String or Symbol, got #{api.class}."
384 version = version || 'v1'
385 return @discovered_apis["#{api}:#{version}"] ||= begin
386 document_base = self.discovery_uri(api, version)
387 discovery_document = self.discovery_document(api, version)
388 if document_base && discovery_document
389 Google::APIClient::API.new(
400 # Returns the method object for a given RPC name and service version.
402 # @param [String, Symbol] rpc_name The RPC name of the desired method.
403 # @param [String, Symbol] rpc_name The API the method is within.
404 # @param [String] version The desired version of the API.
406 # @return [Google::APIClient::Method] The method object.
407 def discovered_method(rpc_name, api, version=nil)
408 if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
410 "Expected String or Symbol, got #{rpc_name.class}."
412 rpc_name = rpc_name.to_s
414 version = version || 'v1'
415 service = self.discovered_api(api, version)
416 if service.to_h[rpc_name]
417 return service.to_h[rpc_name]
424 # Returns the service object with the highest version number.
426 # @note <em>Warning</em>: This method should be used with great care.
427 # As APIs are updated, minor differences between versions may cause
428 # incompatibilities. Requesting a specific version will avoid this issue.
430 # @param [String, Symbol] api The name of the service.
432 # @return [Google::APIClient::API] The service object.
433 def preferred_version(api)
434 if !api.kind_of?(String) && !api.kind_of?(Symbol)
436 "Expected String or Symbol, got #{api.class}."
439 return self.discovered_apis.detect do |a|
440 a.name == api && a.preferred == true
445 # Verifies an ID token against a server certificate. Used to ensure that
446 # an ID token supplied by an untrusted client-side mechanism is valid.
447 # Raises an error if the token is invalid or missing.
449 gem 'jwt', '~> 0.1.4'
453 if !self.authorization.respond_to?(:id_token)
454 raise ArgumentError, (
455 "Current authorization mechanism does not support ID tokens: " +
456 "#{self.authorization.class.to_s}"
458 elsif !self.authorization.id_token
459 raise ArgumentError, (
460 "Could not verify ID token, ID token missing. " +
461 "Scopes were: #{self.authorization.scope.inspect}"
464 check_cached_certs = lambda do
466 for key, cert in @certificates
468 self.authorization.decoded_id_token(cert.public_key)
470 rescue JWT::DecodeError, Signet::UnsafeOperationError
471 # Expected exception. Ignore, ID token has not been validated.
476 if check_cached_certs.call()
479 request = self.generate_request(
480 :http_method => :get,
481 :uri => 'https://www.googleapis.com/oauth2/v1/certs',
482 :authenticated => false
484 response = self.transmit(:request => request)
485 if response.status >= 200 && response.status < 300
486 @certificates.merge!(
487 Hash[MultiJson.load(response.body).map do |key, cert|
488 [key, OpenSSL::X509::Certificate.new(cert)]
491 elsif response.status >= 400
494 exception_type = ClientError
496 exception_type = ServerError
498 exception_type = TransmissionError
500 url = request.to_env(Faraday.default_connection)[:url]
501 raise exception_type,
502 "Could not retrieve certificates from: #{url}"
504 if check_cached_certs.call()
507 raise InvalidIDTokenError,
508 "Could not verify ID token against any available certificate."
515 # Generates a request.
517 # @option options [Google::APIClient::Method, String] :api_method
518 # The method object or the RPC name of the method being executed.
519 # @option options [Hash, Array] :parameters
520 # The parameters to send to the method.
521 # @option options [Hash, Array] :headers The HTTP headers for the request.
522 # @option options [String] :body The body of the request.
523 # @option options [String] :version ("v1")
524 # The service version. Only used if `api_method` is a `String`.
525 # @option options [#generate_authenticated_request] :authorization
526 # The authorization mechanism for the response. Used only if
527 # `:authenticated` is `true`.
528 # @option options [TrueClass, FalseClass] :authenticated (true)
529 # `true` if the request must be signed or somehow
530 # authenticated, `false` otherwise.
532 # @return [Faraday::Request] The generated request.
535 # request = client.generate_request(
536 # :api_method => 'plus.activities.list',
538 # {'collection' => 'public', 'userId' => 'me'}
540 def generate_request(options={})
541 # Note: The merge method on a Hash object will coerce an API Reference
542 # object into a Hash and merge with the default options.
545 :authorization => self.authorization,
547 :user_ip => self.user_ip,
548 :connection => Faraday.default_connection
550 # The Reference object is going to need this to do method ID lookups.
551 options[:client] = self
552 # The default value for the :authenticated option depends on whether an
553 # authorization mechanism has been set.
554 if options[:authorization]
555 options = {:authenticated => true}.merge(options)
557 options = {:authenticated => false}.merge(options)
559 reference = Google::APIClient::Reference.new(options)
560 request = reference.to_request
561 if options[:authenticated]
562 request = self.generate_authenticated_request(
564 :connection => options[:connection]
571 # Signs a request using the current authorization mechanism.
573 # @param [Hash] options a customizable set of options
575 # @return [Faraday::Request] The signed or otherwise authenticated request.
576 def generate_authenticated_request(options={})
577 return authorization.generate_authenticated_request(options)
581 # Transmits the request using the current HTTP adapter.
583 # @option options [Array, Faraday::Request] :request
584 # The HTTP request to transmit.
585 # @option options [String, Symbol] :method
586 # The method for the HTTP request.
587 # @option options [String, Addressable::URI] :uri
588 # The URI for the HTTP request.
589 # @option options [Array, Hash] :headers
590 # The headers for the HTTP request.
591 # @option options [String] :body
592 # The body for the HTTP request.
593 # @option options [Faraday::Connection] :connection
594 # The HTTP connection to use.
596 # @return [Faraday::Response] The response from the server.
597 def transmit(options={})
598 options[:connection] ||= Faraday.default_connection
600 if options[:request].kind_of?(Array)
601 method, uri, headers, body = options[:request]
602 elsif options[:request].kind_of?(Faraday::Request)
603 unless options[:connection]
605 "Faraday::Request used, requires a connection to be provided."
607 method = options[:request].method.to_s.downcase.to_sym
608 uri = options[:connection].build_url(
609 options[:request].path, options[:request].params
611 headers = options[:request].headers || {}
612 body = options[:request].body || ''
615 method = options[:method] || :get
617 headers = options[:headers] || []
618 body = options[:body] || ''
620 headers = headers.to_a if headers.kind_of?(Hash)
621 request_components = {
627 # Verify that we have all pieces required to transmit an HTTP request
628 request_components.each do |(key, value)|
630 raise ArgumentError, "Missing :#{key} parameter."
634 if self.user_agent != nil
635 # If there's no User-Agent header, set one.
636 unless headers.kind_of?(Enumerable)
637 # We need to use some Enumerable methods, relying on the presence of
643 if self.user_agent.kind_of?(String)
644 unless headers.any? { |k, v| k.downcase == 'User-Agent'.downcase }
645 headers = headers.to_a.insert(0, ['User-Agent', self.user_agent])
647 elsif self.user_agent != nil
649 "Expected User-Agent to be String, got #{self.user_agent.class}"
653 request = Faraday::Request.create(method.to_s.downcase.to_sym) do |req|
654 req.url(Addressable::URI.parse(uri))
655 req.headers = Faraday::Utils::Headers.new(headers)
658 request_env = request.to_env(options[:connection])
659 response = options[:connection].app.call(request_env)
664 # Executes a request, wrapping it in a Result object.
666 # @param [Google::APIClient::Method, String] api_method
667 # The method object or the RPC name of the method being executed.
668 # @param [Hash, Array] parameters
669 # The parameters to send to the method.
670 # @param [String] body The body of the request.
671 # @param [Hash, Array] headers The HTTP headers for the request.
672 # @option options [String] :version ("v1")
673 # The service version. Only used if `api_method` is a `String`.
674 # @option options [#generate_authenticated_request] :authorization
675 # The authorization mechanism for the response. Used only if
676 # `:authenticated` is `true`.
677 # @option options [TrueClass, FalseClass] :authenticated (true)
678 # `true` if the request must be signed or somehow
679 # authenticated, `false` otherwise.
681 # @return [Google::APIClient::Result] The result from the API.
684 # result = client.execute(
685 # :api_method => 'plus.activities.list',
686 # :parameters => {'collection' => 'public', 'userId' => 'me'}
689 # @see Google::APIClient#generate_request
691 # This block of code allows us to accept multiple parameter passing
692 # styles, and maintaining some backwards compatibility.
694 # Note: I'm extremely tempted to deprecate this style of execute call.
695 if params.last.respond_to?(:to_hash) && params.size == 1
700 options[:api_method] = params.shift if params.size > 0
701 options[:parameters] = params.shift if params.size > 0
702 options[:body] = params.shift if params.size > 0
703 options[:headers] = params.shift if params.size > 0
704 options[:client] = self
706 reference = Google::APIClient::Reference.new(options)
707 request = self.generate_request(reference)
708 response = self.transmit(
710 :connection => options[:connection]
712 return Google::APIClient::Result.new(reference, request, response)
716 # Same as Google::APIClient#execute, but raises an exception if there was
719 # @see Google::APIClient#execute
720 def execute!(*params)
721 result = self.execute(*params)
723 if result.data.respond_to?(:error) &&
724 result.data.error.respond_to?(:message)
725 # You're going to get a terrible error message if the response isn't
726 # parsed successfully as an error.
727 error_message = result.data.error.message
728 elsif result.data['error'] && result.data['error']['message']
729 error_message = result.data['error']['message']
732 if result.response.status >= 400
733 case result.response.status
735 exception_type = ClientError
736 error_message ||= "A client error has occurred."
738 exception_type = ServerError
739 error_message ||= "A server error has occurred."
741 exception_type = TransmissionError
742 error_message ||= "A transmission error has occurred."
744 raise exception_type, error_message
751 require 'google/api_client/version'