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.
20 require 'google/api_client/errors'
21 require 'google/api_client/environment'
22 require 'google/api_client/discovery'
25 # TODO(bobaman): Document all this stuff.
29 # This class manages APIs communication.
32 # Creates a new Google API client.
34 # @param [Hash] options The configuration parameters for the client.
35 # @option options [Symbol, #generate_authenticated_request] :authorization
37 # The authorization mechanism used by the client. The following
38 # mechanisms are supported out-of-the-box:
40 # <li><code>:two_legged_oauth_1</code></li>
41 # <li><code>:oauth_1</code></li>
42 # <li><code>:oauth_2</code></li>
44 # @option options [String] :host ("www.googleapis.com")
45 # The API hostname used by the client. This rarely needs to be changed.
46 # @option options [String] :application_name
47 # The name and version of the application using the client. This should
48 # be given in the form `"{name}/{version}"`.
49 # @option options [String] :user_agent
50 # ("{app_name} google-api-ruby-client/{version} {os_name}/{os_version}")
51 # The user agent used by the client. Most developers will want to
52 # leave this value alone and use the `:application_name` option instead.
53 def initialize(options={})
54 # Normalize key to String to allow indifferent access.
55 options = options.inject({}) do |accu, (key, value)|
56 accu[key.to_s] = value
59 # Almost all API usage will have a host of 'www.googleapis.com'.
60 self.host = options["host"] || 'www.googleapis.com'
61 # Most developers will want to leave this value alone and use the
62 # application_name option.
63 self.user_agent = options["user_agent"] || (
64 (options["application_name"] || '')
65 'google-api-ruby-client/' + VERSION::STRING +
68 # This is mostly a default for the sake of convenience.
69 # Unlike most other options, this one may be nil, so we check for
70 # the presence of the key rather than checking the value.
71 if options.has_key?("parser")
72 self.parser = options["parser"]
74 require 'google/api_client/parsers/json_parser'
75 # NOTE: Do not rely on this default value, as it may change
76 self.parser = Google::APIClient::JSONParser
78 # The writer method understands a few Symbols and will generate useful
79 # default authentication mechanisms.
80 self.authorization = options["authorization"] || :oauth_2
81 # The HTTP adapter controls all of the HTTP traffic the client generates.
82 # By default, Net::HTTP is used, but adding support for other clients
84 if options["http_adapter"]
85 self.http_adapter = options["http_adapter"]
87 require 'httpadapter/adapters/net_http'
88 # NOTE: Do not rely on this default value, as it may change
89 self.http_adapter = HTTPAdapter::NetHTTPAdapter.new
92 @discovery_documents = {}
99 # Returns the parser used by the client.
101 # @return [#serialize, #parse]
102 # The parser used by the client. Any object that implements both a
103 # <code>#serialize</code> and a <code>#parse</code> method may be used.
104 # If <code>nil</code>, no parsing will be done.
108 # Sets the parser used by the client.
110 # @param [#serialize, #parse] new_parser
111 # The parser used by the client. Any object that implements both a
112 # <code>#serialize</code> and a <code>#parse</code> method may be used.
113 # If <code>nil</code>, no parsing will be done.
114 def parser=(new_parser)
116 !new_parser.respond_to?(:serialize) &&
117 !new_parser.respond_to?(:parse)
119 'Expected parser object to respond to #serialize and #parse.'
125 # Returns the authorization mechanism used by the client.
127 # @return [#generate_authenticated_request] The authorization mechanism.
128 attr_reader :authorization
131 # Sets the authorization mechanism used by the client.
133 # @param [#generate_authenticated_request] new_authorization
134 # The new authorization mechanism.
135 def authorization=(new_authorization)
136 case new_authorization
137 when :oauth_1, :oauth
138 require 'signet/oauth_1/client'
139 # NOTE: Do not rely on this default value, as it may change
140 new_authorization = Signet::OAuth1::Client.new(
141 :temporary_credential_uri =>
142 'https://www.google.com/accounts/OAuthGetRequestToken',
143 :authorization_uri =>
144 'https://www.google.com/accounts/OAuthAuthorizeToken',
145 :token_credential_uri =>
146 'https://www.google.com/accounts/OAuthGetAccessToken',
147 :client_credential_key => 'anonymous',
148 :client_credential_secret => 'anonymous'
150 when :two_legged_oauth_1, :two_legged_oauth
151 require 'signet/oauth_1/client'
152 # NOTE: Do not rely on this default value, as it may change
153 new_authorization = Signet::OAuth1::Client.new(
154 :client_credential_key => nil,
155 :client_credential_secret => nil,
159 require 'signet/oauth_2/client'
160 # NOTE: Do not rely on this default value, as it may change
161 new_authorization = Signet::OAuth2::Client.new(
162 :authorization_uri =>
163 'https://accounts.google.com/o/oauth2/auth',
164 :token_credential_uri =>
165 'https://accounts.google.com/o/oauth2/token'
168 # No authorization mechanism
170 if !new_authorization.respond_to?(:generate_authenticated_request)
172 'Expected authorization mechanism to respond to ' +
173 '#generate_authenticated_request.'
176 @authorization = new_authorization
177 return @authorization
181 # Returns the HTTP adapter used by the client.
183 # @return [HTTPAdapter]
184 # The HTTP adapter object. The object must include the
185 # HTTPAdapter module and conform to its interface.
186 attr_reader :http_adapter
189 # Returns the HTTP adapter used by the client.
191 # @return [HTTPAdapter]
192 # The HTTP adapter object. The object must include the
193 # HTTPAdapter module and conform to its interface.
194 def http_adapter=(new_http_adapter)
195 if new_http_adapter.kind_of?(HTTPAdapter)
196 @http_adapter = new_http_adapter
198 raise TypeError, "Expected HTTPAdapter, got #{new_http_adapter.class}."
203 # The API hostname used by the client.
206 # The API hostname. Should almost always be 'www.googleapis.com'.
210 # The user agent used by the client.
213 # The user agent string used in the User-Agent header.
214 attr_accessor :user_agent
217 # Returns the URI for the directory document.
219 # @return [Addressable::URI] The URI of the directory document.
221 template = Addressable::Template.new(
222 "https://{host}/discovery/v0.3/directory"
224 return template.expand({
230 # Manually registers a URI as a discovery document for a specific version
233 # @param [String, Symbol] api The service name.
234 # @param [String] version The desired version of the service.
235 # @param [Addressable::URI] uri The URI of the discovery document.
236 def register_discovery_uri(api, version, uri)
238 version = version || 'v1'
239 @discovery_uris["#{api}:#{version}"] = uri
243 # Returns the URI for the discovery document.
245 # @param [String, Symbol] api The service name.
246 # @param [String] version The desired version of the service.
247 # @return [Addressable::URI] The URI of the discovery document.
248 def discovery_uri(api, version=nil)
250 version = version || 'v1'
251 return @discovery_uris["#{api}:#{version}"] ||= (begin
252 template = Addressable::Template.new(
253 "https://{host}/discovery/v0.3/describe/" +
265 # Manually registers a pre-loaded discovery document for a specific version
268 # @param [String, Symbol] api The service name.
269 # @param [String] version The desired version of the service.
270 # @param [String, StringIO] discovery_document
271 # The contents of the discovery document.
272 def register_discovery_document(api, version, discovery_document)
274 version = version || 'v1'
275 if discovery_document.kind_of?(StringIO)
276 discovery_document.rewind
277 discovery_document = discovery_document.string
278 elsif discovery_document.respond_to?(:to_str)
279 discovery_document = discovery_document.to_str
282 "Expected String or StringIO, got #{discovery_document.class}."
284 @discovery_documents["#{api}:#{version}"] =
285 JSON.parse(discovery_document)
289 # Returns the parsed directory document.
291 # @return [Hash] The parsed JSON from the directory document.
292 def directory_document
293 return @directory_document ||= (begin
294 request_uri = self.directory_uri
295 request = ['GET', request_uri, [], []]
296 response = self.transmit_request(request)
297 status, headers, body = response
298 if status == 200 # TODO(bobaman) Better status code handling?
299 merged_body = StringIO.new
301 merged_body.write(chunk)
304 JSON.parse(merged_body.string)
306 raise TransmissionError,
307 "Could not retrieve discovery document at: #{request_uri}"
313 # Returns the parsed discovery document.
315 # @param [String, Symbol] api The service name.
316 # @param [String] version The desired version of the service.
317 # @return [Hash] The parsed JSON from the discovery document.
318 def discovery_document(api, version=nil)
320 version = version || 'v1'
321 return @discovery_documents["#{api}:#{version}"] ||= (begin
322 request_uri = self.discovery_uri(api, version)
323 request = ['GET', request_uri, [], []]
324 response = self.transmit_request(request)
325 status, headers, body = response
326 if status == 200 # TODO(bobaman) Better status code handling?
327 merged_body = StringIO.new
329 merged_body.write(chunk)
332 JSON.parse(merged_body.string)
334 raise TransmissionError,
335 "Could not retrieve discovery document at: #{request_uri}"
341 # Returns all APIs published in the directory document.
343 # @return [Array] The list of available APIs.
345 @directory_apis ||= (begin
346 document_base = self.directory_uri
347 if self.directory_document && self.directory_document['items']
348 self.directory_document['items'].map do |discovery_document|
349 ::Google::APIClient::API.new(
361 # Returns the service object for a given service name and service version.
363 # @param [String, Symbol] api The service name.
364 # @param [String] version The desired version of the service.
366 # @return [Google::APIClient::API] The service object.
367 def discovered_api(api, version=nil)
368 if !api.kind_of?(String) && !api.kind_of?(Symbol)
370 "Expected String or Symbol, got #{api.class}."
373 version = version || 'v1'
374 return @discovered_apis["#{api}:#{version}"] ||= begin
375 document_base = self.discovery_uri(api, version)
376 discovery_document = self.discovery_document(api, version)
377 if document_base && discovery_document
378 ::Google::APIClient::API.new(
389 # Returns the method object for a given RPC name and service version.
391 # @param [String, Symbol] rpc_name The RPC name of the desired method.
392 # @param [String] version The desired version of the service.
394 # @return [Google::APIClient::Method] The method object.
395 def discovered_method(rpc_name, api, version=nil)
396 if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
398 "Expected String or Symbol, got #{rpc_name.class}."
400 rpc_name = rpc_name.to_s
402 version = version || 'v1'
403 service = self.discovered_api(api, version)
404 if service.to_h[rpc_name]
405 return service.to_h[rpc_name]
412 # Returns the service object with the highest version number.
414 # @note <em>Warning</em>: This method should be used with great care.
415 # As APIs are updated, minor differences between versions may cause
416 # incompatibilities. Requesting a specific version will avoid this issue.
418 # @param [String, Symbol] api The name of the service.
420 # @return [Google::APIClient::API] The service object.
421 def preferred_version(api)
422 if !api.kind_of?(String) && !api.kind_of?(Symbol)
424 "Expected String or Symbol, got #{api.class}."
427 # TODO(bobaman): Update to use directory API.
428 return self.discovered_apis.detect do |a|
429 a.name == api && a.preferred == true
434 # Generates a request.
436 # @param [Google::APIClient::Method, String] api_method
437 # The method object or the RPC name of the method being executed.
438 # @param [Hash, Array] parameters
439 # The parameters to send to the method.
440 # @param [String] body The body of the request.
441 # @param [Hash, Array] headers The HTTP headers for the request.
442 # @param [Hash] options
443 # The configuration parameters for the request.
444 # - <code>:version</code> —
445 # The service version. Only used if <code>api_method</code> is a
446 # <code>String</code>. Defaults to <code>'v1'</code>.
447 # - <code>:parser</code> —
448 # The parser for the response.
449 # - <code>:authorization</code> —
450 # The authorization mechanism for the response. Used only if
451 # <code>:authenticated</code> is <code>true</code>.
452 # - <code>:authenticated</code> —
453 # <code>true</code> if the request must be signed or otherwise
454 # authenticated, <code>false</code>
455 # otherwise. Defaults to <code>true</code> if an authorization
456 # mechanism has been set, <code>false</code> otherwise.
458 # @return [Array] The generated request.
461 # request = client.generate_request(
462 # 'chili.activities.list',
463 # {'scope' => '@self', 'userId' => '@me', 'alt' => 'json'}
465 # method, uri, headers, body = request
466 def generate_request(
467 api_method, parameters={}, body='', headers=[], options={})
469 :parser => self.parser,
471 :authorization => self.authorization
473 # The default value for the :authenticated option depends on whether an
474 # authorization mechanism has been set.
475 if options[:authorization]
476 options = {:authenticated => true}.merge(options)
478 options = {:authenticated => false}.merge(options)
480 if api_method.kind_of?(String) || api_method.kind_of?(Symbol)
481 api_method = api_method.to_s
482 # This method of guessing the API is unreliable. This will fail for
483 # APIs where the first segment of the RPC name does not match the
484 # service name. However, this is a fallback mechanism anyway.
485 # Developers should be passing in a reference to the method, rather
486 # than passing in a string or symbol. This should raise an error
487 # in the case of a mismatch.
488 api = api_method[/^([^.]+)\./, 1]
489 api_method = self.discovered_method(
490 api_method, api, options[:version]
492 elsif !api_method.kind_of?(::Google::APIClient::Method)
494 "Expected String, Symbol, or Google::APIClient::Method, " +
495 "got #{api_method.class}."
498 raise ArgumentError, "API method could not be found."
500 request = api_method.generate_request(parameters, body, headers)
501 if options[:authenticated]
502 request = self.generate_authenticated_request(:request => request)
508 # Generates a request and transmits it.
510 # @param [Google::APIClient::Method, String] api_method
511 # The method object or the RPC name of the method being executed.
512 # @param [Hash, Array] parameters
513 # The parameters to send to the method.
514 # @param [String] body The body of the request.
515 # @param [Hash, Array] headers The HTTP headers for the request.
516 # @param [Hash] options
517 # The configuration parameters for the request.
518 # - <code>:version</code> —
519 # The service version. Only used if <code>api_method</code> is a
520 # <code>String</code>. Defaults to <code>'v1'</code>.
521 # - <code>:adapter</code> —
523 # - <code>:parser</code> —
524 # The parser for the response.
525 # - <code>:authorization</code> —
526 # The authorization mechanism for the response. Used only if
527 # <code>:authenticated</code> is <code>true</code>.
528 # - <code>:authenticated</code> —
529 # <code>true</code> if the request must be signed or otherwise
530 # authenticated, <code>false</code>
531 # otherwise. Defaults to <code>true</code>.
533 # @return [Array] The response from the API.
536 # response = client.execute(
537 # 'chili.activities.list',
538 # {'scope' => '@self', 'userId' => '@me', 'alt' => 'json'}
540 # status, headers, body = response
541 def execute(api_method, parameters={}, body='', headers=[], options={})
542 request = self.generate_request(
543 api_method, parameters, body, headers, options
545 return self.transmit_request(
547 options[:adapter] || self.http_adapter
552 # Transmits the request using the current HTTP adapter.
554 # @param [Array] request The request to transmit.
555 # @param [#transmit] adapter The HTTP adapter.
557 # @return [Array] The response from the server.
558 def transmit_request(request, adapter=self.http_adapter)
559 if self.user_agent != nil
560 # If there's no User-Agent header, set one.
561 method, uri, headers, body = request
562 unless headers.kind_of?(Enumerable)
563 # We need to use some Enumerable methods, relying on the presence of
569 if self.user_agent.kind_of?(String)
570 unless headers.any? { |k, v| k.downcase == 'User-Agent'.downcase }
571 headers = headers.to_a.insert(0, ['User-Agent', self.user_agent])
573 elsif self.user_agent != nil
575 "Expected User-Agent to be String, got #{self.user_agent.class}"
578 adapter.transmit([method, uri, headers, body])
582 # Signs a request using the current authorization mechanism.
584 # @param [Hash] options The options to pass through.
586 # @return [Array] The signed or otherwise authenticated request.
587 def generate_authenticated_request(options={})
588 return authorization.generate_authenticated_request(options)
593 require 'google/api_client/version'