Failed to load latest commit information.
bin Add youtube partner API, regenerate APIs Apr 14, 2016
generated/google/apis Add slides_v1, regenerate APIs Nov 8, 2016
lib Add slides_v1, regenerate APIs Nov 8, 2016
rakelib Import refactored library. See MIGRATING.MD for details Jun 23, 2015
samples Merge pull request #417 from tknzk/sample-cli-sheetsv4 Jun 9, 2016
script Add slides_v1, regenerate APIs Nov 8, 2016
spec #467 - Restore error handling for failed downloads Sep 19, 2016
third_party Issue #290 - Fix redirects during downloads, only stream body content… Dec 2, 2015
.gitignore ignore IntelliJ files Nov 14, 2013
.rspec Import refactored library. See MIGRATING.MD for details Jun 23, 2015
.rubocop.yml Import refactored library. See MIGRATING.MD for details Jun 23, 2015
.rubocop_todo.yml Import refactored library. See MIGRATING.MD for details Jun 23, 2015
.travis.yml include ruby 2.3.0 in the CI build matrix Feb 25, 2016
.yardopts Import refactored library. See MIGRATING.MD for details Jun 23, 2015 Add slides_v1, regenerate APIs Nov 8, 2016 Import refactored library. See MIGRATING.MD for details Jun 23, 2015
Gemfile Lock down ActiveSupport version to < 5 Aug 8, 2016
LICENSE Basic project skeleton. Jul 28, 2010 Fix readme link Sep 19, 2015 Merge pull request #455 from mortonfox/patch-1 Aug 31, 2016
Rakefile Import refactored library. See MIGRATING.MD for details Jun 23, 2015
api_names.yaml Add slides_v1, regenerate APIs Nov 8, 2016
api_names_out.yaml Add slides_v1, regenerate APIs Nov 8, 2016
google-api-client.gemspec remove thor as runtime dependency Aug 9, 2016
sync.rb Release 0.9.11 Jul 6, 2016

Google API Client


This library is in Alpha. We will make an effort to support the library, but we reserve the right to make incompatible changes when necessary.

Migrating from 0.8.x

Version 0.9 is not compatible with previous versions. See MIGRATING for additional details on how to migrate to the latest version.


Add this line to your application's Gemfile:

gem 'google-api-client', '~> 0.9'

And then execute:

$ bundle

Or install it yourself as:

$ gem install google-api-client


Basic usage

To use an API, include the corresponding generated file and instantiate the service. For example to use the Drive API:

require 'google/apis/drive_v2'

Drive = Google::Apis::DriveV2 # Alias the module
drive =
drive.authorization = ... # See Googleauth or Signet libraries

# Search for files in Drive (first page only)
files = drive.list_files(q: "title contains 'finances'")
files.items.each do |file|
  puts file.title

# Upload a file
metadata = 'My document')
metadata = drive.insert_file(metadata, upload_source: 'test.txt', content_type: 'text/plain')

# Download a file
drive.get_file(, download_dest: '/tmp/myfile.txt')

Naming conventions vs JSON representation

Object properties in the ruby client use the standard ruby convention for naming -- snake_case. This differs from the underlying JSON representation which typically uses camelCase for properties. There are a few notable exceptions to this rule:

  • For properties that are defined as hashes with user-defined keys, no translation is performed on the key.
  • For embedded field masks in requests (for example, the Sheets API), specify the camelCase form when referencing fields.

Outisde those exceptions, if a property is specified using camelCase in a request, it will be ignored during serialization and omitted from the request.


Methods that allow media operations have additional parameters to specify the upload source or download destination.

For uploads, the upload_source parameter can be specified with either a path to a file, an IO stream, or StringIO instance.

For downloads, the download_dest parameter can also be either a path to a file, an IO stream, or StringIO instance.

Both uploads & downloads are resumable. If an error occurs during transmission the request will be automatically retried from the last received byte.

Errors & Retries

Retries are disabled by default, but enabling retries is strongly encouraged. The number of retries can be configured via Google::Apis::RequestOptions. Any number greater than 0 will enable retries.

To enable retries for all services:

Google::Apis::RequestOptions.default.retries = 5

With retries enabled globally, retries can be disabled for specific calls by including a retry value of 0 in the request options:

drive.insert_file(metadata, upload_source: 'test.txt', content_type: 'text/plain', options: { retries: 0 })

When retries are enabled, if a server or rate limit error occurs during a request it is automatically retried with an exponentially increasing delay on subsequent retries. If a request can not be retried or if the maximum number of retries is exceeded, an exception is thrown.


A block can be specified when making calls. If present, the block will be called with the result or error, rather than returning the result from the call or raising the error. Example:

# Search for files in Drive (first page only)
drive.list_files(q: "title contains 'finances'") do |res, err|
  if err
    # Handle error
    # Handle response

This calling style is required when making batch requests as responses are not available until the entire batch is complete.


To fetch multiple pages of data, use the fetch_all method to wrap the paged query. This returns an Enumerable that automatically fetches additional pages as needed.

# List all calendar events
now =
items = calendar.fetch_all do |token|
                        single_events: true,
                        order_by: 'startTime',
                        time_min: now,
                        page_token: token)
items.each { |event| puts event.summary }

For APIs that use a field other than items to contain the results, an alternate field name can be supplied.

# List all files in Drive
items = drive.fetch_all(items: :files) { |token| drive.list_files(page_token: token) }
items.each { |file| puts }


Multiple requests can be batched together into a single HTTP request to reduce overhead. Batched calls are executed in parallel and the responses processed once all results are available

# Fetch a bunch of files by ID
ids = ['file_id_1', 'file_id_2', 'file_id_3', 'file_id_4']
drive.batch do |drive|
  ids.each do |id|
    drive.get_file(id) do |res, err|
      # Handle response

Media operations -- uploads & downloads -- can not be included in batch with other requests.

However, some APIs support batch uploads. To upload multiple files in a batch, use the batch_upload method instead. Batch uploads should only be used when uploading multiple small files. For large files, upload files individually to take advantage of the libraries built-in resumable upload support.


While the API will always return instances of schema classes, plain hashes are accepted in method calls for convenience. Hash keys must be symbols matching the attribute names on the corresponding object the hash is meant to replace. For example:

file = {id: '123', title: 'My document', labels: { starred: true }}
file = drive.create_file(file, {}) # Returns a Drive::File instance

is equivalent to:

file = '123', title: 'My document')
file.labels = true)
file = drive.update_file(file) # Returns a Drive::File instance

IMPORTANT: Be careful when supplying hashes for request objects. If it is the last argument to a method, ruby will interpret the hash as keyword arguments. To prevent this, appending an empty hash as an extra parameter will avoid misinterpretation.

file = {id: '123', title: 'My document', labels: { starred: true }}
file = drive.create_file(file) # Raises ArgumentError: unknown keywords: id, title, labels
file = drive.create_file(file, {}) # Returns a Drive::File instance


OAuth 2 is used to authorize applications. This library uses both Signet and Google Auth Library for Ruby for OAuth 2 support.

The Google Auth Library for Ruby provides an implementation of [application default credentials] for Ruby. It offers a simple way to get authorization credentials for use in calling Google APIs, best suited for cases when the call needs to have the same identity and authorization level for the application independent of the user. This is the recommended approach to authorize calls to Cloud APIs, particularly when you're building an application that uses Google Compute Engine.

For per-user authorization, use Signet to obtain user authorization.

Passing authorization to requests

Authorization can be specified for the entire client, for an individual service instance, or on a per-request basis.

Set authorization for all service:

Google::Apis::RequestOptions.default.authorization = authorization
# Services instantiated after this will inherit the authorization

On a per-service level:

drive =
drive.authorization = authorization

# All requests made with this service will use the same authorization


drive.get_file('123', options: { authorization: authorization })

Authorization using API keys

Some APIs allow using an API key instead of OAuth2 tokens. For these APIs, set the key attribute of the service instance. For example:

require 'google/apis/translate_v2'

translate =
translate.key = 'YOUR_API_KEY_HERE'
result = translate.list_translations('Hello world!', 'es', source: 'en')
puts result.translations.first.translated_text

Authorization using environment variables

The GoogleAuth Library for Ruby also supports authorization via environment variables if you do not want to check in developer credentials or private keys. Simply set the following variables for your application:



The client includes a Logger instance that can be used to capture debugging information.

To set the logging level for the client:

Google::Apis.logger.level = Logger::DEBUG

When running in a Rails environment, the client will default to using ::Rails.logger. If you prefer to use a separate logger instance for API calls, this can be changed via one of two ways.

The first is to provide a new logger instance:

Google::Apis.logger =

The second is to set the environment variable GOOGLE_API_USE_RAILS_LOGGER to any value other than 'true'


Samples for versions 0.9 and onward can be found in the samples directory. Contributions for additional samples are welcome. See CONTRIBUTING.

Samples for previous versions can be found in the samples folder.

Generating APIs

For Cloud Endpoints or other APIs not included in the gem, ruby code can be generated from the discovery document.

To generate from a local discovery file:

$ generate-api gen <outdir> --file=<path>

A URL can also be specified:

$ generate-api gen <outdir> --url=<url>


  • ETag support (if-not-modified)
  • Caching
  • Model validations


This library is licensed under Apache 2.0. Full license text is available in LICENSE.




Please report bugs at the project on Github. Don't hesitate to ask questions about the client or APIs on StackOverflow.