2019-10-29 20:40:28 +00:00
# Google API Client [![Documentation](https://img.shields.io/badge/docs-Google%3A%3AApis-red.svg)](https://googleapis.dev/ruby/google-api-client/latest/Google/Apis.html) [![Gem Version](https://badge.fury.io/rb/google-api-client.svg)](https://badge.fury.io/rb/google-api-client)
2010-07-28 19:30:56 +00:00
2018-04-12 20:12:59 +00:00
These client libraries are officially supported by Google. However, the libraries are considered complete and are in maintenance mode. This means that we will address critical bugs and security issues but will not add any new features.
2017-07-07 16:57:36 +00:00
2018-04-12 20:12:59 +00:00
## Google Cloud Platform
2017-07-07 16:57:36 +00:00
2018-04-12 20:12:59 +00:00
For Google Cloud Platform APIs such as Datastore, Cloud Storage or Pub/Sub, we recommend using [GoogleCloudPlatform/google-cloud-ruby ](https://github.com/GoogleCloudPlatform/google-cloud-ruby ) which is under active development.
2017-05-17 21:09:37 +00:00
2015-04-17 00:28:38 +00:00
## Migrating from 0.8.x
2010-07-28 19:30:56 +00:00
2017-03-30 19:39:09 +00:00
See [MIGRATING ](MIGRATING.md ) for additional details on how to migrate to the latest version.
2010-07-28 19:30:56 +00:00
2019-11-13 23:47:51 +00:00
## Documentation
Learn how to use the Google API Client Library for Ruby with these guides:
### Usage Guides
- [Getting Started ](docs/getting-started.md )
- [Installation ](docs/installation.md )
- [Auth ](docs/auth.md )
- [API Keys ](docs/api-keys.md )
- [OAuth 2.0 ](docs/oauth.md )
- [OAuth 2.0 for Web Server Applications ](docs/oauth-web.md )
- [OAuth 2.0 for Installed Applications ](docs/oauth-installed.md )
- [OAuth 2.0 for Server to Server Applications ](docs/oauth-server.md )
- [Client Secrets ](docs/client-secrets.md )
- How to...
- [Use Logging ](docs/logging.md )
- [Upload Media ](docs/media-upload.md )
- [Use Pagination ](docs/pagination.md )
- [Improve Performance ](docs/performance.md )
### Reference Documentation
- Reference documentation for [google-api-client ](https://googleapis.dev/ruby/google-api-client/latest/index.html ).
2015-04-17 00:28:38 +00:00
## Installation
Add this line to your application's Gemfile:
2014-10-03 20:37:40 +00:00
2015-04-17 00:28:38 +00:00
```ruby
2019-11-13 23:47:51 +00:00
gem 'google-api-client', '~> 0.34'
2015-06-28 22:45:41 +00:00
2015-04-17 00:28:38 +00:00
```
2014-10-03 20:37:40 +00:00
2015-04-17 00:28:38 +00:00
And then execute:
2012-10-04 22:48:49 +00:00
2015-04-17 00:28:38 +00:00
$ bundle
2012-10-04 22:48:49 +00:00
2015-04-17 00:28:38 +00:00
Or install it yourself as:
2012-10-04 22:48:49 +00:00
2016-01-15 01:42:44 +00:00
$ gem install google-api-client
2012-10-04 22:48:49 +00:00
2015-04-17 00:28:38 +00:00
## Usage
### Basic usage
To use an API, include the corresponding generated file and instantiate the service. For example to use the Drive API:
2010-07-28 19:30:56 +00:00
2013-04-29 02:29:39 +00:00
```ruby
2015-04-17 00:28:38 +00:00
require 'google/apis/drive_v2'
Drive = Google::Apis::DriveV2 # Alias the module
drive = Drive::DriveService.new
2016-03-11 22:43:51 +00:00
drive.authorization = ... # See Googleauth or Signet libraries
2015-04-17 00:28:38 +00:00
# Search for files in Drive (first page only)
files = drive.list_files(q: "title contains 'finances'")
files.items.each do |file|
puts file.title
end
# Upload a file
metadata = Drive::File.new(title: 'My document')
metadata = drive.insert_file(metadata, upload_source: 'test.txt', content_type: 'text/plain')
# Download a file
drive.get_file(metadata.id, download_dest: '/tmp/myfile.txt')
2013-04-29 02:29:39 +00:00
```
2019-11-26 01:29:00 +00:00
An example to use the Content API (Google Merchant Center)
```ruby
require 'google/apis/content_v2'
require 'googleauth' # https://github.com/googleapis/google-auth-library-ruby
Content = Google::Apis::ContentV2 # Alias the module
content = Content::ShoppingContentService.new
scope = 'https://www.googleapis.com/auth/content'
merchant_id = # Merchant ID found on dashboard
content.authorization = Google::Auth::ServiceAccountCredentials.make_creds(
json_key_io: File.open('./content-api-key.json'),
scope: scope)
content.authorization.fetch_access_token!
# Service methods: https://googleapis.dev/ruby/google-api-client/latest/Google/Apis/ContentV2/ShoppingContentService.html
content.list_datafeeds(merchant_id) # Returns Google::Apis::ContentV2::ListDatafeedsResponse
```
2016-08-31 17:53:34 +00:00
### 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.
2012-10-04 22:48:49 +00:00
2017-01-29 07:25:56 +00:00
Outside those exceptions, if a property is specified using camelCase in a request, it will be ignored during serialization and omitted from the request.
2016-08-31 17:57:21 +00:00
2015-04-17 00:28:38 +00:00
### Media
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.
2012-10-04 22:48:49 +00:00
2015-04-17 00:28:38 +00:00
### Errors & Retries
2012-10-04 22:48:49 +00:00
2015-04-17 00:28:38 +00:00
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:
2012-10-04 22:48:49 +00:00
2013-04-29 02:29:39 +00:00
```ruby
2015-04-17 00:28:38 +00:00
Google::Apis::RequestOptions.default.retries = 5
2013-04-29 02:29:39 +00:00
```
2012-10-04 22:48:49 +00:00
2015-04-17 00:28:38 +00:00
With retries enabled globally, retries can be disabled for specific calls by including a retry value of 0 in the
request options:
2012-10-04 22:48:49 +00:00
2013-04-29 02:29:39 +00:00
```ruby
2015-04-17 00:28:38 +00:00
drive.insert_file(metadata, upload_source: 'test.txt', content_type: 'text/plain', options: { retries: 0 })
2013-04-29 02:29:39 +00:00
```
2012-10-04 22:48:49 +00:00
2015-04-17 00:28:38 +00:00
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.
2012-10-04 22:48:49 +00:00
2015-04-17 00:28:38 +00:00
### Callbacks
2016-03-01 06:59:54 +00:00
A block can be specified when making calls. If present, the block will be called with the result or error, rather than
2015-04-17 00:28:38 +00:00
returning the result from the call or raising the error. Example:
2014-09-25 15:44:12 +00:00
2015-04-17 00:28:38 +00:00
```ruby
# Search for files in Drive (first page only)
drive.list_files(q: "title contains 'finances'") do |res, err|
if err
# Handle error
else
# Handle response
end
end
2013-04-29 02:29:39 +00:00
```
2012-10-04 22:48:49 +00:00
2015-04-17 00:28:38 +00:00
This calling style is required when making batch requests as responses are not available until the entire batch
is complete.
2012-10-04 22:48:49 +00:00
2016-03-11 22:43:51 +00:00
### Paging
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.
```ruby
# List all calendar events
now = Time.now.iso8601
items = calendar.fetch_all do |token|
calendar.list_events('primary',
single_events: true,
order_by: 'startTime',
time_min: now,
page_token: token)
end
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.
```ruby
# List all files in Drive
items = drive.fetch_all(items: :files) { |token| drive.list_files(page_token: token) }
items.each { |file| puts file.name }
```
2015-04-17 00:28:38 +00:00
### Batches
2012-10-04 22:48:49 +00:00
2015-04-17 00:28:38 +00:00
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
2013-06-16 12:15:06 +00:00
2013-01-05 00:13:03 +00:00
2015-04-17 00:28:38 +00:00
```ruby
# 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
end
end
end
```
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
2015-08-19 16:02:37 +00:00
take advantage of the libraries built-in resumable upload support.
2015-04-17 00:28:38 +00:00
### Hashes
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:
2015-03-24 01:06:02 +00:00
```ruby
2015-04-17 00:28:38 +00:00
file = {id: '123', title: 'My document', labels: { starred: true }}
2016-01-22 01:55:48 +00:00
file = drive.create_file(file, {}) # Returns a Drive::File instance
2015-03-24 01:06:02 +00:00
```
2015-04-17 00:28:38 +00:00
is equivalent to:
2015-03-24 01:06:02 +00:00
2013-04-29 02:29:39 +00:00
```ruby
2015-04-17 00:28:38 +00:00
file = Drive::File.new(id: '123', title: 'My document')
file.labels = Drive::File::Labels.new(starred: true)
file = drive.update_file(file) # Returns a Drive::File instance
2013-06-16 12:15:06 +00:00
```
2016-01-22 01:55:48 +00:00
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.
```ruby
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
```
2017-04-03 18:20:00 +00:00
### Using raw JSON
To handle JSON serialization or deserialization in the application, set `skip_serialization` or
or `skip_deserializaton` options respectively. When setting `skip_serialization` in a request,
the body object must be a string representing the serialized JSON.
When setting `skip_deserialization` to true, the response from the API will likewise
be a string containing the raw JSON from the server.
2016-01-22 01:55:48 +00:00
2015-04-17 00:28:38 +00:00
## Authorization
2013-09-10 22:31:24 +00:00
2015-04-17 00:28:38 +00:00
[OAuth 2 ](https://developers.google.com/accounts/docs/OAuth2 ) is used to authorize applications. This library uses
both [Signet ](https://github.com/google/signet ) and
[Google Auth Library for Ruby ](https://github.com/google/google-auth-library-ruby ) for OAuth 2 support.
2014-01-22 23:40:06 +00:00
2015-04-17 00:28:38 +00:00
The [Google Auth Library for Ruby ](https://github.com/google/google-auth-library-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.
2014-01-22 23:40:06 +00:00
2015-04-17 00:28:38 +00:00
For per-user authorization, use [Signet ](https://github.com/google/signet ) to obtain user authorization.
2013-09-10 22:31:24 +00:00
2015-04-17 00:28:38 +00:00
### Passing authorization to requests
2010-10-14 00:04:36 +00:00
2015-04-17 00:28:38 +00:00
Authorization can be specified for the entire client, for an individual service instance, or on a per-request basis.
2010-10-14 00:04:36 +00:00
2015-04-17 00:28:38 +00:00
Set authorization for all service:
2010-07-28 19:30:56 +00:00
2013-04-29 02:29:39 +00:00
```ruby
2015-04-17 00:28:38 +00:00
Google::Apis::RequestOptions.default.authorization = authorization
# Services instantiated after this will inherit the authorization
```
2013-06-16 12:15:06 +00:00
2015-04-17 00:28:38 +00:00
On a per-service level:
```ruby
drive = Google::Apis::DriveV2::DriveService.new
drive.authorization = authorization
2013-06-16 12:15:06 +00:00
2015-04-17 00:28:38 +00:00
# All requests made with this service will use the same authorization
2013-04-29 02:29:39 +00:00
```
2013-06-16 12:15:06 +00:00
2015-04-17 00:28:38 +00:00
Per-request:
2012-10-04 22:48:49 +00:00
2013-04-29 02:29:39 +00:00
```ruby
2015-04-17 00:28:38 +00:00
drive.get_file('123', options: { authorization: authorization })
2013-04-29 02:29:39 +00:00
```
2012-10-04 22:48:49 +00:00
2015-12-02 00:51:53 +00:00
### 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:
```ruby
require 'google/apis/translate_v2'
translate = Google::Apis::TranslateV2::TranslateService.new
translate.key = 'YOUR_API_KEY_HERE'
2016-01-20 20:24:20 +00:00
result = translate.list_translations('Hello world!', 'es', source: 'en')
2015-12-02 00:51:53 +00:00
puts result.translations.first.translated_text
```
2016-03-01 16:23:46 +00:00
### Authorization using environment variables
The [GoogleAuth Library for Ruby ](https://github.com/google/google-auth-library-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:
```sh
GOOGLE_ACCOUNT_TYPE="YOUR ACCOUNT TYPE" # ie. 'service'
GOOGLE_CLIENT_EMAIL="YOUR GOOGLE DEVELOPER EMAIL"
GOOGLE_PRIVATE_KEY="YOUR GOOGLE DEVELOPER API KEY"
```
2016-04-14 19:54:58 +00:00
## Logging
The client includes a `Logger` instance that can be used to capture debugging information.
2018-03-22 15:34:27 +00:00
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, you can provide a new logger instance:
2016-04-14 19:54:58 +00:00
```ruby
2018-03-22 15:34:27 +00:00
Google::Apis.logger = Logger.new(STDERR)
2016-04-14 19:54:58 +00:00
```
2018-03-22 15:34:27 +00:00
Or, you can set the environment variable `GOOGLE_API_USE_RAILS_LOGGER` to any value other than `'true'` ; this will send all logging information to STDOUT.
2016-04-14 19:54:58 +00:00
2018-03-22 15:34:27 +00:00
To set the logging level for the client:
2016-04-14 19:54:58 +00:00
```ruby
2018-03-22 15:34:27 +00:00
Google::Apis.logger.level = Logger::DEBUG
2016-04-14 19:54:58 +00:00
```
2019-06-24 20:18:22 +00:00
## Customizing endpoints
By default, client objects will connect to the default Google endpoints for =
their respective APIs. If you need to connect to a regional endpoint, a test
endpoint, or other custom endpoint, modify the `root_url` attribute of the
client object. For example:
```ruby
require "google/apis/docs_v1"
docs_service = Google::Apis::DocsV1::DocsService.new
docs_service.root_url = "https://my-custom-docs-endpoint.example.com/"
document = docs_service.get_document("my-document-id")
```
2016-01-07 19:41:45 +00:00
## Samples
2017-04-03 18:20:00 +00:00
See the [samples ](https://github.com/google/google-api-ruby-client/tree/master/samples ) for examples on how to use the client library for various
2017-03-30 19:39:09 +00:00
services.
2016-01-07 19:41:45 +00:00
2020-12-07 20:12:09 +00:00
Contributions for additional samples are welcome. See [CONTRIBUTING ](.github/CONTRIBUTING.md ).
2016-01-07 19:41:45 +00:00
2015-04-17 00:28:38 +00:00
## Generating APIs
2012-10-04 22:48:49 +00:00
2015-04-17 00:28:38 +00:00
For [Cloud Endpoints ](https://cloud.google.com/endpoints/ ) or other APIs not included in the gem, ruby code can be
generated from the discovery document.
2012-10-04 22:48:49 +00:00
2015-04-17 00:28:38 +00:00
To generate from a local discovery file:
2013-06-16 12:15:06 +00:00
2015-04-17 00:28:38 +00:00
$ generate-api gen < outdir > --file=< path >
2012-10-04 22:48:49 +00:00
2015-04-17 00:28:38 +00:00
A URL can also be specified:
2012-10-25 23:21:00 +00:00
2015-04-17 00:28:38 +00:00
$ generate-api gen < outdir > --url=< url >
2012-10-25 23:21:00 +00:00
2015-04-17 00:28:38 +00:00
## TODO
2012-10-25 23:21:00 +00:00
2015-04-17 00:28:38 +00:00
* ETag support (if-not-modified)
* Caching
* Model validations
2012-10-26 00:02:59 +00:00
2018-09-24 18:54:55 +00:00
## Supported Ruby Versions
2020-12-07 20:12:09 +00:00
This library is currently supported on Ruby 1.9+.
2018-09-24 18:54:55 +00:00
However, Ruby 2.4 or later is strongly recommended, as earlier releases have
reached or are nearing end-of-life. After March 31, 2019, Google will provide
official support only for Ruby versions that are considered current and
supported by Ruby Core (that is, Ruby versions that are either in normal
maintenance or in security maintenance).
See https://www.ruby-lang.org/en/downloads/branches/ for further details.
2015-04-17 00:28:38 +00:00
## License
This library is licensed under Apache 2.0. Full license text is
2016-08-23 04:21:09 +00:00
available in [LICENSE ](LICENSE ).
2015-04-17 00:28:38 +00:00
2016-01-21 04:52:58 +00:00
## Contributing
2012-10-26 00:02:59 +00:00
2019-05-09 20:01:41 +00:00
See [CONTRIBUTING ](.github/CONTRIBUTING.md ).
2015-04-17 00:28:38 +00:00
## Support
2015-03-24 01:06:02 +00:00
2015-04-17 00:28:38 +00:00
Please [report bugs at the project on Github ](https://github.com/google/google-api-ruby-client/issues ). Don't
hesitate to [ask questions ](http://stackoverflow.com/questions/tagged/google-api-ruby-client ) about the client or APIs
on [StackOverflow ](http://stackoverflow.com ).