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/v1/apis"
224 return template.expand({"host" => self.host})
228 # Manually registers a URI as a discovery document for a specific version
231 # @param [String, Symbol] api The service name.
232 # @param [String] version The desired version of the service.
233 # @param [Addressable::URI] uri The URI of the discovery document.
234 def register_discovery_uri(api, version, uri)
236 version = version || 'v1'
237 @discovery_uris["#{api}:#{version}"] = uri
241 # Returns the URI for the discovery document.
243 # @param [String, Symbol] api The service name.
244 # @param [String] version The desired version of the service.
245 # @return [Addressable::URI] The URI of the discovery document.
246 def discovery_uri(api, version=nil)
248 version = version || 'v1'
249 return @discovery_uris["#{api}:#{version}"] ||= (begin
250 template = Addressable::Template.new(
251 "https://{host}/discovery/v1/apis/" +
252 "{api}/{version}/rest"
263 # Manually registers a pre-loaded discovery document for a specific version
266 # @param [String, Symbol] api The service name.
267 # @param [String] version The desired version of the service.
268 # @param [String, StringIO] discovery_document
269 # The contents of the discovery document.
270 def register_discovery_document(api, version, discovery_document)
272 version = version || 'v1'
273 if discovery_document.kind_of?(StringIO)
274 discovery_document.rewind
275 discovery_document = discovery_document.string
276 elsif discovery_document.respond_to?(:to_str)
277 discovery_document = discovery_document.to_str
280 "Expected String or StringIO, got #{discovery_document.class}."
282 @discovery_documents["#{api}:#{version}"] =
283 JSON.parse(discovery_document)
287 # Returns the parsed directory document.
289 # @return [Hash] The parsed JSON from the directory document.
290 def directory_document
291 return @directory_document ||= (begin
292 request_uri = self.directory_uri
293 request = ['GET', request_uri, [], []]
294 response = self.transmit_request(request)
295 status, headers, body = response
296 if status == 200 # TODO(bobaman) Better status code handling?
297 merged_body = StringIO.new
299 merged_body.write(chunk)
302 JSON.parse(merged_body.string)
304 raise TransmissionError,
305 "Could not retrieve discovery document at: #{request_uri}"
311 # Returns the parsed discovery document.
313 # @param [String, Symbol] api The service name.
314 # @param [String] version The desired version of the service.
315 # @return [Hash] The parsed JSON from the discovery document.
316 def discovery_document(api, version=nil)
318 version = version || 'v1'
319 return @discovery_documents["#{api}:#{version}"] ||= (begin
320 request_uri = self.discovery_uri(api, version)
321 request = ['GET', request_uri, [], []]
322 response = self.transmit_request(request)
323 status, headers, body = response
324 if status == 200 # TODO(bobaman) Better status code handling?
325 merged_body = StringIO.new
327 merged_body.write(chunk)
330 JSON.parse(merged_body.string)
332 raise TransmissionError,
333 "Could not retrieve discovery document at: #{request_uri}"
339 # Returns all APIs published in the directory document.
341 # @return [Array] The list of available APIs.
343 @directory_apis ||= (begin
344 document_base = self.directory_uri
345 if self.directory_document && self.directory_document['items']
346 self.directory_document['items'].map do |discovery_document|
347 ::Google::APIClient::API.new(
359 # Returns the service object for a given service name and service version.
361 # @param [String, Symbol] api The service name.
362 # @param [String] version The desired version of the service.
364 # @return [Google::APIClient::API] The service object.
365 def discovered_api(api, version=nil)
366 if !api.kind_of?(String) && !api.kind_of?(Symbol)
368 "Expected String or Symbol, got #{api.class}."
371 version = version || 'v1'
372 return @discovered_apis["#{api}:#{version}"] ||= begin
373 document_base = self.discovery_uri(api, version)
374 discovery_document = self.discovery_document(api, version)
375 if document_base && discovery_document
376 ::Google::APIClient::API.new(
387 # Returns the method object for a given RPC name and service version.
389 # @param [String, Symbol] rpc_name The RPC name of the desired method.
390 # @param [String] version The desired version of the service.
392 # @return [Google::APIClient::Method] The method object.
393 def discovered_method(rpc_name, api, version=nil)
394 if !rpc_name.kind_of?(String) && !rpc_name.kind_of?(Symbol)
396 "Expected String or Symbol, got #{rpc_name.class}."
398 rpc_name = rpc_name.to_s
400 version = version || 'v1'
401 service = self.discovered_api(api, version)
402 if service.to_h[rpc_name]
403 return service.to_h[rpc_name]
410 # Returns the service object with the highest version number.
412 # @note <em>Warning</em>: This method should be used with great care.
413 # As APIs are updated, minor differences between versions may cause
414 # incompatibilities. Requesting a specific version will avoid this issue.
416 # @param [String, Symbol] api The name of the service.
418 # @return [Google::APIClient::API] The service object.
419 def preferred_version(api)
420 if !api.kind_of?(String) && !api.kind_of?(Symbol)
422 "Expected String or Symbol, got #{api.class}."
425 # TODO(bobaman): Update to use directory API.
426 return self.discovered_apis.detect do |a|
427 a.name == api && a.preferred == true
432 # Generates a request.
434 # @param [Google::APIClient::Method, String] api_method
435 # The method object or the RPC name of the method being executed.
436 # @param [Hash, Array] parameters
437 # The parameters to send to the method.
438 # @param [String] body The body of the request.
439 # @param [Hash, Array] headers The HTTP headers for the request.
440 # @param [Hash] options
441 # The configuration parameters for the request.
442 # - <code>:version</code> —
443 # The service version. Only used if <code>api_method</code> is a
444 # <code>String</code>. Defaults to <code>'v1'</code>.
445 # - <code>:parser</code> —
446 # The parser for the response.
447 # - <code>:authorization</code> —
448 # The authorization mechanism for the response. Used only if
449 # <code>:authenticated</code> is <code>true</code>.
450 # - <code>:authenticated</code> —
451 # <code>true</code> if the request must be signed or otherwise
452 # authenticated, <code>false</code>
453 # otherwise. Defaults to <code>true</code> if an authorization
454 # mechanism has been set, <code>false</code> otherwise.
456 # @return [Array] The generated request.
459 # request = client.generate_request(
460 # 'chili.activities.list',
461 # {'scope' => '@self', 'userId' => '@me', 'alt' => 'json'}
463 # method, uri, headers, body = request
464 def generate_request(
465 api_method, parameters={}, body='', headers=[], options={})
467 :parser => self.parser,
469 :authorization => self.authorization
471 # The default value for the :authenticated option depends on whether an
472 # authorization mechanism has been set.
473 if options[:authorization]
474 options = {:authenticated => true}.merge(options)
476 options = {:authenticated => false}.merge(options)
478 if api_method.kind_of?(String) || api_method.kind_of?(Symbol)
479 api_method = api_method.to_s
480 # This method of guessing the API is unreliable. This will fail for
481 # APIs where the first segment of the RPC name does not match the
482 # service name. However, this is a fallback mechanism anyway.
483 # Developers should be passing in a reference to the method, rather
484 # than passing in a string or symbol. This should raise an error
485 # in the case of a mismatch.
486 api = api_method[/^([^.]+)\./, 1]
487 api_method = self.discovered_method(
488 api_method, api, options[:version]
490 elsif !api_method.kind_of?(::Google::APIClient::Method)
492 "Expected String, Symbol, or Google::APIClient::Method, " +
493 "got #{api_method.class}."
496 raise ArgumentError, "API method could not be found."
498 request = api_method.generate_request(parameters, body, headers)
499 if options[:authenticated]
500 request = self.generate_authenticated_request(:request => request)
506 # Generates a request and transmits it.
508 # @param [Google::APIClient::Method, String] api_method
509 # The method object or the RPC name of the method being executed.
510 # @param [Hash, Array] parameters
511 # The parameters to send to the method.
512 # @param [String] body The body of the request.
513 # @param [Hash, Array] headers The HTTP headers for the request.
514 # @param [Hash] options
515 # The configuration parameters for the request.
516 # - <code>:version</code> —
517 # The service version. Only used if <code>api_method</code> is a
518 # <code>String</code>. Defaults to <code>'v1'</code>.
519 # - <code>:adapter</code> —
521 # - <code>:parser</code> —
522 # The parser for the response.
523 # - <code>:authorization</code> —
524 # The authorization mechanism for the response. Used only if
525 # <code>:authenticated</code> is <code>true</code>.
526 # - <code>:authenticated</code> —
527 # <code>true</code> if the request must be signed or otherwise
528 # authenticated, <code>false</code>
529 # otherwise. Defaults to <code>true</code>.
531 # @return [Array] The response from the API.
534 # response = client.execute(
535 # 'chili.activities.list',
536 # {'scope' => '@self', 'userId' => '@me', 'alt' => 'json'}
538 # status, headers, body = response
539 def execute(api_method, parameters={}, body='', headers=[], options={})
540 request = self.generate_request(
541 api_method, parameters, body, headers, options
543 return self.transmit_request(
545 options[:adapter] || self.http_adapter
550 # Transmits the request using the current HTTP adapter.
552 # @param [Array] request The request to transmit.
553 # @param [#transmit] adapter The HTTP adapter.
555 # @return [Array] The response from the server.
556 def transmit_request(request, adapter=self.http_adapter)
557 if self.user_agent != nil
558 # If there's no User-Agent header, set one.
559 method, uri, headers, body = request
560 unless headers.kind_of?(Enumerable)
561 # We need to use some Enumerable methods, relying on the presence of
567 if self.user_agent.kind_of?(String)
568 unless headers.any? { |k, v| k.downcase == 'User-Agent'.downcase }
569 headers = headers.to_a.insert(0, ['User-Agent', self.user_agent])
571 elsif self.user_agent != nil
573 "Expected User-Agent to be String, got #{self.user_agent.class}"
576 adapter.transmit([method, uri, headers, body])
580 # Signs a request using the current authorization mechanism.
582 # @param [Hash] options The options to pass through.
584 # @return [Array] The signed or otherwise authenticated request.
585 def generate_authenticated_request(options={})
586 return authorization.generate_authenticated_request(options)
591 require 'google/api_client/version'