50c4a38b50
This PR was generated using Autosynth. 🌈 <details><summary>Log from Synthtool</summary> ``` 2020-12-15 02:59:15,588 synthtool [DEBUG] > Executing /home/kbuilder/.cache/synthtool/google-api-ruby-client/synth.py. On branch autosynth-notebooks-v1 nothing to commit, working tree clean 2020-12-15 02:59:15,618 synthtool [DEBUG] > Running: docker run --rm -v/home/kbuilder/.cache/synthtool/google-api-ruby-client:/workspace -v/var/run/docker.sock:/var/run/docker.sock -w /workspace --entrypoint script/synth.rb gcr.io/cloud-devrel-kokoro-resources/yoshi-ruby/autosynth notebooks v1 DEBUG:synthtool:Running: docker run --rm -v/home/kbuilder/.cache/synthtool/google-api-ruby-client:/workspace -v/var/run/docker.sock:/var/run/docker.sock -w /workspace --entrypoint script/synth.rb gcr.io/cloud-devrel-kokoro-resources/yoshi-ruby/autosynth notebooks v1 bundle install Don't run Bundler as root. Bundler can ask for sudo if it is needed, and installing your bundle as root will break this application for all non-root users on this machine. The dependency jruby-openssl (>= 0) will be unused by any of the platforms Bundler is installing for. Bundler is installing for ruby but the dependency is only for java. To add those platforms to the bundle, run `bundle lock --add-platform java`. Fetching gem metadata from https://rubygems.org/......... Fetching gem metadata from https://rubygems.org/. Resolving dependencies... Fetching rake 11.3.0 Installing rake 11.3.0 Fetching concurrent-ruby 1.1.7 Installing concurrent-ruby 1.1.7 Fetching i18n 1.8.5 Installing i18n 1.8.5 Fetching minitest 5.14.2 Installing minitest 5.14.2 Fetching thread_safe 0.3.6 Installing thread_safe 0.3.6 Fetching tzinfo 1.2.8 Installing tzinfo 1.2.8 Fetching activesupport 5.0.7.2 Installing activesupport 5.0.7.2 Fetching public_suffix 4.0.6 Installing public_suffix 4.0.6 Fetching addressable 2.7.0 Installing addressable 2.7.0 Fetching ast 2.4.1 Installing ast 2.4.1 Using bundler 2.1.4 Fetching byebug 11.1.3 Installing byebug 11.1.3 with native extensions Fetching coderay 1.1.3 Installing coderay 1.1.3 Fetching json 2.4.0 Installing json 2.4.0 with native extensions Fetching docile 1.3.2 Installing docile 1.3.2 Fetching simplecov-html 0.10.2 Installing simplecov-html 0.10.2 Fetching simplecov 0.16.1 Installing simplecov 0.16.1 Using sync 0.5.0 Fetching tins 1.26.0 Installing tins 1.26.0 Fetching term-ansicolor 1.7.1 Installing term-ansicolor 1.7.1 Fetching thor 0.20.3 Installing thor 0.20.3 Fetching coveralls 0.8.23 Installing coveralls 0.8.23 Fetching crack 0.4.4 Installing crack 0.4.4 Fetching declarative 0.0.20 Installing declarative 0.0.20 Fetching declarative-option 0.1.0 Installing declarative-option 0.1.0 Fetching diff-lcs 1.4.4 Installing diff-lcs 1.4.4 Fetching dotenv 2.7.6 Installing dotenv 2.7.6 Fetching fakefs 0.20.1 Installing fakefs 0.20.1 Fetching multipart-post 2.1.1 Installing multipart-post 2.1.1 Fetching ruby2_keywords 0.0.2 Installing ruby2_keywords 0.0.2 Fetching faraday 1.1.0 Installing faraday 1.1.0 Fetching gems 1.2.0 Installing gems 1.2.0 Fetching github-markup 1.7.0 Installing github-markup 1.7.0 Fetching jwt 2.2.2 Installing jwt 2.2.2 Fetching memoist 0.16.2 Installing memoist 0.16.2 Fetching multi_json 1.15.0 Installing multi_json 1.15.0 Fetching os 0.9.6 Installing os 0.9.6 Fetching signet 0.14.0 Installing signet 0.14.0 Fetching googleauth 0.14.0 Installing googleauth 0.14.0 Fetching httpclient 2.8.3 Installing httpclient 2.8.3 Fetching mini_mime 1.0.2 Installing mini_mime 1.0.2 Fetching uber 0.1.0 Installing uber 0.1.0 Fetching representable 3.0.4 Installing representable 3.0.4 Fetching retriable 3.1.2 Installing retriable 3.1.2 Fetching rexml 3.2.4 Installing rexml 3.2.4 Using google-api-client 0.52.0 from source at `.` Fetching google-id-token 1.4.2 Installing google-id-token 1.4.2 Fetching hashdiff 1.0.1 Installing hashdiff 1.0.1 Fetching mime-types-data 3.2020.1104 Installing mime-types-data 3.2020.1104 Fetching mime-types 3.3.1 Installing mime-types 3.3.1 Fetching multi_xml 0.6.0 Installing multi_xml 0.6.0 Fetching httparty 0.18.1 Installing httparty 0.18.1 Fetching rspec-support 3.10.0 Installing rspec-support 3.10.0 Fetching rspec-core 3.10.0 Installing rspec-core 3.10.0 Fetching rspec-expectations 3.10.0 Installing rspec-expectations 3.10.0 Fetching rspec-mocks 3.10.0 Installing rspec-mocks 3.10.0 Fetching rspec 3.10.0 Installing rspec 3.10.0 Fetching json_spec 1.1.5 Installing json_spec 1.1.5 Fetching launchy 2.5.0 Installing launchy 2.5.0 Fetching little-plugger 1.1.4 Installing little-plugger 1.1.4 Fetching logging 2.3.0 Installing logging 2.3.0 Fetching method_source 1.0.0 Installing method_source 1.0.0 Fetching opencensus 0.5.0 Installing opencensus 0.5.0 Fetching parallel 1.20.1 Installing parallel 1.20.1 Fetching parser 2.7.2.0 Installing parser 2.7.2.0 Fetching powerpack 0.1.3 Installing powerpack 0.1.3 Fetching pry 0.13.1 Installing pry 0.13.1 Fetching pry-byebug 3.9.0 Installing pry-byebug 3.9.0 Fetching yard 0.9.25 Installing yard 0.9.25 Fetching pry-doc 0.13.5 Installing pry-doc 0.13.5 Fetching rainbow 2.2.2 Installing rainbow 2.2.2 with native extensions Fetching redcarpet 3.5.0 Installing redcarpet 3.5.0 with native extensions Fetching redis 3.3.5 Installing redis 3.3.5 Fetching rmail 1.1.4 Installing rmail 1.1.4 Fetching ruby-progressbar 1.10.1 Installing ruby-progressbar 1.10.1 Fetching unicode-display_width 1.7.0 Installing unicode-display_width 1.7.0 Fetching rubocop 0.49.1 Installing rubocop 0.49.1 Fetching webmock 2.3.2 Installing webmock 2.3.2 Bundle complete! 31 Gemfile dependencies, 78 gems now installed. Use `bundle info [gemname]` to see where a bundled gem is installed. Post-install message from i18n: HEADS UP! i18n 1.1 changed fallbacks to exclude default locale. But that may break your application. If you are upgrading your Rails application from an older version of Rails: Please check your Rails app for 'config.i18n.fallbacks = true'. If you're using I18n (>= 1.1.0) and Rails (< 5.2.2), this should be 'config.i18n.fallbacks = [I18n.default_locale]'. If not, fallbacks will be broken in your app by I18n 1.1.x. If you are starting a NEW Rails application, you can ignore this notice. For more info see: https://github.com/svenfuchs/i18n/releases/tag/v1.1.0 Post-install message from httparty: When you HTTParty, you must party hard! echo a | bundle exec bin/generate-api gen generated --api=notebooks.v1 --names-out=/workspace/api_names_out.yaml Loading notebooks, version v1 from https://raw.githubusercontent.com/googleapis/discovery-artifact-manager/master/discoveries/notebooks.v1.json conflict google/apis/notebooks_v1.rb <is/notebooks_v1.rb? (enter "h" for help) [Ynaqdhm] a force google/apis/notebooks_v1.rb conflict google/apis/notebooks_v1/service.rb force google/apis/notebooks_v1/service.rb conflict google/apis/notebooks_v1/classes.rb force google/apis/notebooks_v1/classes.rb conflict google/apis/notebooks_v1/representations.rb force google/apis/notebooks_v1/representations.rb conflict /workspace/api_names_out.yaml force /workspace/api_names_out.yaml 2020-12-15 02:59:40,973 synthtool [DEBUG] > Wrote metadata to generated/google/apis/notebooks_v1/synth.metadata. DEBUG:synthtool:Wrote metadata to generated/google/apis/notebooks_v1/synth.metadata. ``` </details> Full log will be available here: https://source.cloud.google.com/results/invocations/906c06e9-ae37-4b71-ba31-d21a411f86e7/targets - [ ] To automatically regenerate this PR, check this box. |
||
---|---|---|
.github | ||
.kokoro | ||
bin | ||
docs | ||
generated/google/apis | ||
lib | ||
rakelib | ||
samples | ||
script | ||
spec | ||
.gitignore | ||
.repo-metadata.json | ||
.rspec | ||
.rubocop.yml | ||
.rubocop_todo.yml | ||
.yardopts | ||
CHANGELOG.md | ||
CODE_OF_CONDUCT.md | ||
Gemfile | ||
LICENSE | ||
MIGRATING.md | ||
OVERVIEW.md | ||
README.md | ||
Rakefile | ||
api_list_config.yaml | ||
api_names.yaml | ||
api_names_out.yaml | ||
google-api-client.gemspec | ||
synth.metadata | ||
synth.py |
README.md
Google API Client
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.
Google Cloud Platform
For Google Cloud Platform APIs such as Datastore, Cloud Storage or Pub/Sub, we recommend using GoogleCloudPlatform/google-cloud-ruby which is under active development.
Migrating from 0.8.x
See MIGRATING for additional details on how to migrate to the latest version.
Documentation
Learn how to use the Google API Client Library for Ruby with these guides:
Usage Guides
- Getting Started
- Installation
- Auth
- How to...
Reference Documentation
- Reference documentation for google-api-client.
Installation
Add this line to your application's Gemfile:
gem 'google-api-client', '~> 0.34'
And then execute:
$ bundle
Or install it yourself as:
$ gem install google-api-client
Usage
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::DriveService.new
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
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')
An example to use the Content API (Google Merchant Center)
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
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.
Outside those exceptions, if a property is specified using camelCase in a request, it will be ignored during serialization and omitted from the request.
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.
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.
Callbacks
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
else
# Handle response
end
end
This calling style is required when making batch requests as responses are not available until the entire batch is complete.
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.
# 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.
# List all files in Drive
items = drive.fetch_all(items: :files) { |token| drive.list_files(page_token: token) }
items.each { |file| puts file.name }
Batches
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
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
take advantage of the libraries built-in resumable upload support.
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:
file = {id: '123', title: 'My document', labels: { starred: true }}
file = drive.create_file(file, {}) # Returns a Drive::File instance
is equivalent to:
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
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
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.
Authorization
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 = Google::Apis::DriveV2::DriveService.new
drive.authorization = authorization
# All requests made with this service will use the same authorization
Per-request:
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 = Google::Apis::TranslateV2::TranslateService.new
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:
GOOGLE_ACCOUNT_TYPE="YOUR ACCOUNT TYPE" # ie. 'service'
GOOGLE_CLIENT_EMAIL="YOUR GOOGLE DEVELOPER EMAIL"
GOOGLE_PRIVATE_KEY="YOUR GOOGLE DEVELOPER API KEY"
Logging
The client includes a Logger
instance that can be used to capture debugging information.
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:
Google::Apis.logger = Logger.new(STDERR)
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.
To set the logging level for the client:
Google::Apis.logger.level = Logger::DEBUG
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:
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")
Samples
See the samples for examples on how to use the client library for various services.
Contributions for additional samples are welcome. See CONTRIBUTING.
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>
TODO
- ETag support (if-not-modified)
- Caching
- Model validations
Supported Ruby Versions
This library is currently supported on Ruby 1.9+. 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.
License
This library is licensed under Apache 2.0. Full license text is available in LICENSE.
Contributing
See CONTRIBUTING.
Support
Please report bugs at the project on Github. Don't hesitate to ask questions about the client or APIs on StackOverflow.