docs: add OVERVIEW.md and guides from developers.google.com (#847)

[closes #793, closes #794, closes #795, closes #796, closes #797, closes #798, closes #799, closes #800, closes #801, closes #802]
This commit is contained in:
Chris Smith 2019-11-13 16:47:51 -07:00 committed by GitHub
parent bf6333e31a
commit 1135e74c48
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 1321 additions and 4 deletions

View File

@ -3,10 +3,23 @@
--verbose
--markup-provider=redcarpet
--markup=markdown
--main OVERVIEW.md
lib/**/*.rb
generated/**/*.rb
-
README.md
OVERVIEW.md
docs/getting-started.md
docs/installation.md
docs/auth.md
docs/api-keys.md
docs/oauth.md
docs/oauth-web.md
docs/oauth-installed.md
docs/oauth-server.md
docs/client-secrets.md
docs/logging.md
docs/media-upload.md
docs/pagination.md
docs/performance.md
MIGRATING.md
CONTRIBUTING.md
LICENSE

36
OVERVIEW.md Normal file
View File

@ -0,0 +1,36 @@
# Google API Client Library for Ruby Docs
The Google API Client Library for Ruby is designed for Ruby
client-application developers. It offers simple, flexible
access to many Google APIs.
## Features
- Call Google APIs simply
- Handle Auth with fewer lines of code
- Use standard tooling for installation
## Documentation
Learn how to use the Google API Client Library for Ruby with these guides:
### Usage Guides
- {file:docs/getting-started.md Getting Started}
- {file:docs/installation.md Installation}
- {file:docs/auth.md Auth}
- {file:docs/api-keys.md API Keys}
- {file:docs/oauth.md OAuth 2.0}
- {file:docs/oauth-web.md OAuth 2.0 for Web Server Applications}
- {file:docs/oauth-installed.md OAuth 2.0 for Installed Applications}
- {file:docs/oauth-server.md OAuth 2.0 for Server to Server Applications}
- {file:docs/client-secrets.md Client Secrets}
- How to...
- {file:docs/logging.md Use Logging}
- {file:docs/media-upload.md Upload Media}
- {file:docs/pagination.md Use Pagination}
- {file:docs/performance.md Improve Performance}
### Reference Documentation
- Reference documentation for [google-api-client](https://googleapis.dev/ruby/google-api-client/latest/index.html).

View File

@ -10,12 +10,37 @@ For Google Cloud Platform APIs such as Datastore, Cloud Storage or Pub/Sub, we r
See [MIGRATING](MIGRATING.md) 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](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).
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'google-api-client', '~> 0.11'
gem 'google-api-client', '~> 0.34'
```

20
docs/api-keys.md Normal file
View File

@ -0,0 +1,20 @@
# API Keys
When calling APIs that do not access private user data, you can use simple API keys. These keys are used to authenticate your application for accounting purposes. The Google Developers Console documentation also describes [API keys](https://developers.google.com/console/help/using-keys).
> Note: If you do need to access private user data, you must use OAuth 2.0. See [Using OAuth 2.0 for Installed Applications](oauth-installed.md), [Using OAuth 2.0 for Server to Server Applications](oauth-server.md), and [Using OAuth 2.0 for Web Server Applications](oauth-web.md) for more information.
## Using API Keys
To use API keys, set the `key` attribute on service objects. For example:
```ruby
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
```
All calls made using that service object will include your API key.

53
docs/auth.md Normal file
View File

@ -0,0 +1,53 @@
# Authentication Overview
This document is an overview of how authentication, authorization, and accounting are accomplished. For all API calls, your application needs to be authenticated. When an API accesses a user's private data, your application must also be authorized by the user to access the data. For example, accessing a public Google+ post would not require user authorization, but accessing a user's private calendar would. Also, for quota and billing purposes, all API calls involve accounting. This document summarizes the protocols used by Google APIs and provides links to more information.
## Access types
It is important to understand the basics of how API authentication and authorization are handled. All API calls must use either simple or authorized access (defined below). Many API methods require authorized access, but some can use either. Some API methods that can use either behave differently, depending on whether you use simple or authorized access. See the API's method documentation to determine the appropriate access type.
### 1. Simple API access (API keys)
These API calls do not access any private user data. Your application must authenticate itself as an application belonging to your Google API Console project. This is needed to measure project usage for accounting purposes.
**API key:** To authenticate your application, use an [API key](api-keys.md) for your API Console project. Every simple access call your application makes must include this key.
> **Warning:** Keep your API key private. If someone obtains your key, they could use it to consume your quota or incur charges against your API Console project.
### 2. Authorized API access (OAuth 2.0)
These API calls access private user data. Before you can call them, the user that has access to the private data must grant your application access. Therefore, your application must be authenticated, the user must grant access for your application, and the user must be authenticated in order to grant that access. All of this is accomplished with OAuth 2.0 and libraries written for it.
**Scope:** Each API defines one or more scopes that declare a set of operations permitted. For example, an API might have read-only and read-write scopes. When your application requests access to user data, the request must include one or more scopes. The user needs to approve the scope of access your application is requesting.
**Refresh and access tokens:** When a user grants your application access, the OAuth 2.0 authorization server provides your application with refresh and access tokens. These tokens are only valid for the scope requested. Your application uses access tokens to authorize API calls. Access tokens expire, but refresh tokens do not. Your application can use a refresh token to acquire a new access token.
> **Warning:** Keep refresh and access tokens private. If someone obtains your tokens, they could use them to access private user data.
**Client ID and client secret:** These strings uniquely identify your application and are used to acquire tokens. They are created for your project on the [API Console](https://console.developers.google.com/). There are three types of client IDs, so be sure to get the correct type for your application:
- [Web application](https://developers.google.com/accounts/docs/OAuth2WebServer) client IDs
- [Installed application](https://developers.google.com/accounts/docs/OAuth2InstalledApp) client IDs
- [Service Account](https://developers.google.com/accounts/docs/OAuth2ServiceAccount) client IDs
> **Warning:** Keep your client secret private. If someone obtains your client secret, they could use it to consume your quota, incur charges against your Console project, and request access to user data.
## Using API keys
More information and examples for API keys are provided on the [API Keys](api-keys.md) page.
## Using OAuth 2.0
More information and examples for OAuth 2.0 are provided on the [OAuth 2.0](oauth.md) page.
## 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"
```

69
docs/client-secrets.md Normal file
View File

@ -0,0 +1,69 @@
# Client Secrets
The Google APIs Client Library for Ruby uses the `client_secrets.json` file format for storing the `client_id`, `client_secret`, and other OAuth 2.0 parameters.
See [Creating authorization credentials](https://developers.google.com/identity/protocols/OAuth2WebServer#creatingcred) for how to obtain a `client_secrets.json` file.
The `client_secrets.json` file format is a [JSON](http://www.json.org/) formatted file containing the client ID, client secret, and other OAuth 2.0 parameters. Here is an example client_secrets.json file for a web application:
```json
{
"web": {
"client_id": "asdfjasdljfasdkjf",
"client_secret": "1912308409123890",
"redirect_uris": ["https://www.example.com/oauth2callback"],
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token"
}
}
```
Here is an example client_secrets.json file for an installed application:
```json
{
"installed": {
"client_id": "837647042410-75ifg...usercontent.com",
"client_secret":"asdlkfjaskd",
"redirect_uris": ["http://localhost", "urn:ietf:wg:oauth:2.0:oob"],
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token"
}
}
```
The format defines one of two client ID types:
- `web`: Web application.
- `installed`: Installed application.
The `web` and `installed` sub-objects have the following mandatory members:
- `client_id` (string): The client ID.
- `client_secret` (string): The client secret.
- `redirect_uris` (list of strings): A list of valid redirection endpoint URIs. This list should match the list entered for the client ID on the [API Access pane](https://code.google.com/apis/console#:access) of the Google APIs Console.
- `auth_uri` (string): The authorization server endpoint URI.
- `token_uri` (string): The token server endpoint URI.
All of the above members are mandatory. The following optional parameters may appear:
- `client_email` (string) The service account email associated with the client.
- `auth_provider_x509_cert_url` (string) The URL of the public x509 certificate, used to verify the signature on JWTs, such as ID tokens, signed by the authentication provider.
- `client_x509_cert_url` (string) The URL of the public x509 certificate, used to verify JWTs signed by the client.
The following shows how you can use a client_secrets.json file and the Google::APIClient::ClientSecrets class to create a new authorization object:
```rb
require 'google/api_client/client_secrets'
CLIENT_SECRETS = Google::APIClient::ClientSecrets.load
authorization = CLIENT_SECRETS.to_authorization
# You can then use this with an API client, e.g.:
client.authorization = authorization
```
## Motivation
Traditionally providers of OAuth endpoints have relied upon cut-and-paste as the way users of their service move the client id and secret from a registration page into working code. That can be error prone, along with it being an incomplete picture of all the information that is needed to get OAuth 2.0 working, which requires knowing all the endpoints and configuring a Redirect Endpoint. If service providers start providing a downloadable client_secrets.json file for client information and client libraries start consuming client_secrets.json then a large amount of friction in implementing OAuth 2.0 can be reduced.

340
docs/getting-started.md Normal file
View File

@ -0,0 +1,340 @@
# Getting Started
This document provides all the basic information you need to start using the library. It covers important library concepts, shows examples for various use cases, and gives links to more information.
## Setup
There are a few setup steps you need to complete before you can use this library:
1. If you don't already have a Google account, [sign up](https://www.google.com/accounts).
2. If you have never created a Google APIs Console project, read the [Managing Projects page](http://developers.google.com/console/help/managing-projects) and create a project in the [Google API Console](https://console.developers.google.com/).
## Authentication and authorization
It is important to understand the basics of how API authentication and authorization are handled. All API calls must use either simple or authorized access (defined below). Many API methods require authorized access, but some can use either. Some API methods that can use either behave differently, depending on whether you use simple or authorized access. See the API's method documentation to determine the appropriate access type.
### 1. Simple API access (API keys)
These API calls do not access any private user data. Your application must authenticate itself as an application belonging to your Google Cloud project. This is needed to measure project usage for accounting purposes.
**API key**: To authenticate your application, use an [API key](https://cloud.google.com/docs/authentication/api-keys) for your Google Cloud Console project. Every simple access call your application makes must include this key.
> **Warning**: Keep your API key private. If someone obtains your key, they could use it to consume your quota or incur charges against your Google Cloud project.
### 2. Authorized API access (OAuth 2.0)
These API calls access private user data. Before you can call them, the user that has access to the private data must grant your application access. Therefore, your application must be authenticated, the user must grant access for your application, and the user must be authenticated in order to grant that access. All of this is accomplished with [OAuth 2.0](https://developers.google.com/identity/protocols/OAuth2) and libraries written for it.
* **Scope**: Each API defines one or more scopes that declare a set of operations permitted. For example, an API might have read-only and read-write scopes. When your application requests access to user data, the request must include one or more scopes. The user needs to approve the scope of access your application is requesting.
* **Refresh and access tokens**: When a user grants your application access, the OAuth 2.0 authorization server provides your application with refresh and access tokens. These tokens are only valid for the scope requested. Your application uses access tokens to authorize API calls. Access tokens expire, but refresh tokens do not. Your application can use a refresh token to acquire a new access token.
> **Warning**: Keep refresh and access tokens private. If someone obtains your tokens, they could use them to access private user data.
* **Client ID and client secret**: These strings uniquely identify your application and are used to acquire tokens. They are created for your Google Cloud project on the [API Access pane](https://console.developers.google.com/apis/credentials) of the Google Cloud. There are several types of client IDs, so be sure to get the correct type for your application:
* Web application client IDs
* Installed application client IDs
* [Service Account](https://developers.google.com/identity/protocols/OAuth2ServiceAccount) client IDs
> **Warning**: Keep your client secret private. If someone obtains your client secret, they could use it to consume your quota, incur charges against your Google Cloud project, and request access to user data.
## Installation
Add this line to your application's Gemfile:
```ruby
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:
```ruby
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')
```
### 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:
```ruby
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:
```ruby
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:
```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
```
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.
```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 }
```
### 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
```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
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:
```ruby
file = {id: '123', title: 'My document', labels: { starred: true }}
file = drive.create_file(file, {}) # Returns a Drive::File instance
```
is equivalent to:
```ruby
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.
```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
```
### 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](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.
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.
For per-user authorization, use [Signet](https://github.com/google/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:
```ruby
Google::Apis::RequestOptions.default.authorization = authorization
# Services instantiated after this will inherit the authorization
```
On a per-service level:
```ruby
drive = Google::Apis::DriveV2::DriveService.new
drive.authorization = authorization
# All requests made with this service will use the same authorization
```
Per-request:
```ruby
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:
```ruby
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
```
## 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")
```
## Samples
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
services.
## Generating APIs
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.
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>
## 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](LICENSE).
## Support
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).

0
docs/installation.md Normal file
View File

34
docs/logging.md Normal file
View File

@ -0,0 +1,34 @@
# Logging
This page provides logging tips to help you debug your applications.
## Accessing the Logger
Logging is enabled by default in this library using Ruby's standard Logger class.
You can access the library logger with the logger property of Google::Apis.
## Log Level
You can set the logging level to one of the following:
- FATAL (least amount of logging)
- ERROR
- WARN
- INFO
- DEBUG (most amount of logging)
In the following code, the logging level is set to DEBUG and the Google Plus API is called:
```rb
require 'google/apis/plus_v1'
Google::Apis.logger.level = Logger::DEBUG
plus = Google::Apis::PlusV1::PlusService.new
activities = plus.list_activities('103354693083460731603', 'public')
```
The output of this code should include debug info:
```
D, [2015-06-26T14:33:42.583914 #12144] DEBUG -- : Sending HTTP get https://www.googleapis.com/plus/v1/people/103354693083460731603/activities/public?key=...
```

25
docs/media-upload.md Normal file
View File

@ -0,0 +1,25 @@
## Media Upload
For APIs that support file uploads, two additional keyword parameters are available on the method. The parameter upload_source specifies the content to upload while content_type indicates the MIME type. The upload source may be either a file name, IO, or StringIO instance.
For example, to upload a file named 'mymovie.m4v' to Google Drive:
```rb
require 'google/apis/drive_v2'
drive = Google::Apis::DriveV2:DriveService.new
drive.authorization = ...
drive.insert_file({title: 'My Favorite Movie'}, upload_source: 'mymovie.m4v',
content_type: 'video/mp4')
```
## Resumable media
For large media files, you can use resumable media uploads to send files, which allows files to be uploaded in smaller chunks. This is especially useful if you are transferring large files, and the likelihood of a network interruption or some other transmission failure is high. It can also reduce your bandwidth usage in the event of network failures because you don't have to restart large file uploads from the beginning.
To use resumable uploads, enable retries by setting the retry count to any value greater than 0. The client will automatically resume the upload in the event of an error, up to the configured number of retries.:
```rb
drive.insert_file(file_metadata, upload_source: 'mymovie.m4v',
content_type: 'video/mp4', options: { retries: 3 } )
```

191
docs/oauth-installed.md Normal file
View File

@ -0,0 +1,191 @@
# Using OAuth 2.0 for Installed Applications
The Google APIs Client Library for Ruby supports using OAuth 2.0 in applications that are installed on a device such as a computer, a cell phone, or a tablet. Installed apps are distributed to individual machines, and it is assumed that these apps cannot keep secrets. These apps might access a Google API while the user is present at the app, or when the app is running in the background.
This document is for you if:
- You are writing an installed app for a platform other than Android or iOS, and
- Your installed app will run on devices that have a system browser and rich input capabilities, such as devices with full keyboards.
If you are writing an app for Android or iOS, use [Google Sign-In](https://developers.google.com/identity) to authenticate your users. The Google Sign-In button manages the OAuth 2.0 flow both for authentication and for obtaining authorization to Google APIs. To add the Google Sign-In button, follow the steps for [Android](https://developers.google.com/identity/sign-in/android) or [iOS](https://developers.google.com/identity/sign-in/ios).
If your app will run on devices that do not have access to a system browser, or devices with limited input capabilities (for example, if your app will run on game consoles, video cameras, or printers), then see [Using OAuth 2.0 for Devices](https://developers.google.com/accounts/docs/OAuth2ForDevices).
## Overview
To use OAuth 2.0 in a locally-installed application, first create application credentials for your project in the API Console.
Then, when your application needs to access a user's data with a Google API, your application sends the user to Google's OAuth 2.0 server. The OAuth 2.0 server authenticates the user and obtains consent from the user for your application to access the user's data.
Next, Google's OAuth 2.0 server sends a single-use authorization code to your application, either in the title bar of the browser or in the query string of an HTTP request to the local host. Your application exchanges this authorization code for an access token.
Finally, your application can use the access token to call Google APIs.
This flow is similar to the one shown in the [Using OAuth 2.0 for Web Server Applications](docs/oauth-server.md), but with three differences:
- When creating a client ID, you specify that your application is an Installed application. This results in a different value for the redirect_uri parameter.
- The client ID and client secret obtained from the API Console are embedded in the source code of your application. In this context, the client secret is obviously not treated as a secret.
- The authorization code can be returned to your application in the title bar of the browser or in the query string of an HTTP request to the local host.
## Creating application credentials
All applications that use OAuth 2.0 must have credentials that identify the application to the OAuth 2.0 server. Applications that have these credentials can access the APIs that you enabled for your project.
To obtain application credentials for your project, complete these steps:
1. Open the [Credentials page](https://console.developers.google.com/apis/credentials) in the API Console.
1. If you haven't done so already, create your OAuth 2.0 credentials by clicking **Create new Client ID** under the **OAuth** heading and selecting the **Installed application** type. Next, look for your application's client ID and client secret in the relevant table.
Download the client_secrets.json file and securely store it in a location that only your application can access.
> **Important:** Do not store the client_secrets.json file in a publicly-accessible location, and if you share the source code to your application—for example, on GitHub—store the client_secrets.json file outside of your source tree to avoid inadvertently sharing your client credentials.
## Configuring the client object
Use the client application credentials that you created to configure a client object in your application. When you configure a client object, you specify the scopes your application needs to access, along with a redirect URI, which will handle the response from the OAuth 2.0 server.
### Choosing a redirect URI
When you create a client ID in the [Google API Console](https://console.developers.google.com/), two redirect_uri parameters are created for you: `urn:ietf:wg:oauth:2.0:oob` and `http://localhost`. The value your application uses determines how the authorization code is returned to your application.
#### http://localhost
This value signals to the Google Authorization Server that the authorization code should be returned as a query string parameter to the web server on the client. You can specify a port number without changing the [Google API Console](https://console.developers.google.com/) configuration. To receive the authorization code using this URI, your application must be listening on the local web server. This is possible on many, but not all, platforms. If your platform supports it, this is the recommended mechanism for obtaining the authorization code.
> **Note:** In some cases, although it is possible to listen, other software (such as a Windows firewall) prevents delivery of the message without significant client configuration.
#### urn:ietf:wg:oauth:2.0:oob
This value signals to the Google Authorization Server that the authorization code should be returned in the title bar of the browser, with the page text prompting the user to copy the code and paste it in the application. This is useful when the client (such as a Windows application) cannot listen on an HTTP port without significant client configuration.
When you use this value, your application can then detect that the page has loaded, and can read the title of the HTML page to obtain the authorization code. It is then up to your application to close the browser window if you want to ensure that the user never sees the page that contains the authorization code. The mechanism for doing this varies from platform to platform.
If your platform doesn't allow you to detect that the page has loaded or read the title of the page, you can have the user paste the code back to your application, as prompted by the text in the confirmation page that the OAuth 2.0 server generates.
#### urn:ietf:wg:oauth:2.0:oob:auto
urn:ietf:wg:oauth:2.0:oob:auto
This is identical to urn:ietf:wg:oauth:2.0:oob, but the text in the confirmation page that the OAuth 2.0 server generates won't instruct the user to copy the authorization code, but instead will simply ask the user to close the window.
This is useful when your application reads the title of the HTML page (by checking window titles on the desktop, for example) to obtain the authorization code, but can't close the page on its own.
### Creating the object
To create a client object from the client_secrets.json file, use the to_authorization method of a ClientSecrets object. For example, to request read-only access to a user's Google Drive:
```rb
require 'google/api_client'
client_secrets = Google::APIClient::ClientSecrets.load
auth_client = client_secrets.to_authorization
auth_client.update!(
:scope => 'https://www.googleapis.com/auth/drive.metadata.readonly',
:redirect_uri => 'urn:ietf:wg:oauth:2.0:oob'
)
```
Your application uses the client object to perform OAuth 2.0 operations, such as generating authorization request URIs and applying access tokens to HTTP requests.
## Sending users to Google's OAuth 2.0 server
When your application needs to access a user's data, redirect the user to Google's OAuth 2.0 server.
1. Generate a URL to request access from Google's OAuth 2.0 server:
`auth_uri = auth_client.authorization_uri.to_s`
2. Open auth_uri in a browser:
```rb
require 'launchy'
Launchy.open(auth_uri)
```
Google's OAuth 2.0 server will authenticate the user and obtain consent from the user for your application to access the requested scopes. The response will be sent back to your application using the redirect URI specified in the client object.
## Handling the OAuth 2.0 server response
The OAuth 2.0 server responds to your application's access request by using the URI specified in the request.
If the user approves the access request, then the response contains an authorization code. If the user does not approve the request, the response contains an error message. Depending on the redirect URI that you specified, the response is in the query string of an HTTP request to the local host, or in a web page, from which the user can copy and paste the authorization code.
To exchange an authorization code for an access token, use the fetch_access_token! method:
```rb
auth_client.code = auth_code
auth_client.fetch_access_token!
```
## Calling Google APIs
Use the auth_client object to call Google APIs by completing the following steps:
1. Build a service object for the API that you want to call. You build a a service object by calling the discovered_api function with the name and version of the API. For example, to call version 2 of the Drive API:
```rb
require 'google/apis/drive_v2'
drive = Google::Apis::DriveV2::DriveService.new
drive.authorization = auth_client
```
2. Make requests to the API service using the interface provided by the service object. For example, to list the files in the authenticated user's Google Drive:
```rb
files = drive.list_files()
```
## Complete example
The following example prints a JSON-formatted list of files in a user's Google Drive after the user authenticates and gives consent for the application to access the user's Drive files.
```rb
require 'google/apis/drive_v2'
require 'google/api_client/client_secrets'
require 'launchy'
client_secrets = Google::APIClient::ClientSecrets.load
auth_client = client_secrets.to_authorization
auth_client.update!(
:scope => 'https://www.googleapis.com/auth/drive.metadata.readonly',
:redirect_uri => 'urn:ietf:wg:oauth:2.0:oob'
)
auth_uri = auth_client.authorization_uri.to_s
Launchy.open(auth_uri)
puts 'Paste the code from the auth response page:'
auth_client.code = gets
auth_client.fetch_access_token!
drive = Google::Apis::DriveV2::DriveService.new
drive.authorization = auth_client
files = drive.list_files
files.items.each do |file|
puts file.title
end
```
If you want to use a local web server to handle the OAuth 2.0 response, you can use the InstalledAppFlow helper to simplify the process. For example:
```rb
require 'google/apis/drive_v2'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
client_secrets = Google::APIClient::ClientSecrets.load
flow = Google::APIClient::InstalledAppFlow.new(
:client_id => client_secrets.client_id,
:client_secret => client_secrets.client_secret,
:scope => 'https://www.googleapis.com/auth/drive.metadata.readonly',
:port => 5000)
drive = Google::Apis::DriveV2::DriveService.new
drive.authorization = flow.authorize
files = drive.list_files
files.items.each do |file|
puts file.title
end
```

135
docs/oauth-server.md Normal file
View File

@ -0,0 +1,135 @@
# Using OAuth 2.0 for Server to Server Applications
The Google APIs Client Library for Ruby supports using OAuth 2.0 for server-to-server interactions such as those between a web application and a Google service. For this scenario you need a service account, which is an account that belongs to your application instead of to an individual end user. Your application calls Google APIs on behalf of the service account, so users aren't directly involved. This scenario is sometimes called "two-legged OAuth," or "2LO." (The related term "three-legged OAuth" refers to scenarios in which your application calls Google APIs on behalf of end users, and in which user consent is sometimes required.)
Typically, an application uses a service account when the application uses Google APIs to work with its own data rather than a user's data. For example, an application that uses [Google Cloud Datastore](https://cloud.google.com/datastore/) for data persistence would use a service account to authenticate its calls to the Google Cloud Datastore API.
If you have a G Suite domain—if you use [G Suite](https://gsuite.google.com/), for example—an administrator of the G Suite domain can authorize an application to access user data on behalf of users in the G Suite domain. For example, an application that uses the [Google Calendar API](https://developers.google.com/calendar/) to add events to the calendars of all users in a G Suite domain would use a service account to access the Google Calendar API on behalf of users. Authorizing a service account to access data on behalf of users in a domain is sometimes referred to as "delegating domain-wide authority" to a service account.
> **Note:** When you use [G Suite Marketplace](https://www.google.com/enterprise/marketplace/) to install an application for your domain, the required permissions are automatically granted to the application. You do not need to manually authorize the service accounts that the application uses.
> **Note:** Although you can use service accounts in applications that run from a Google Apps domain, service accounts are not members of your Google Apps account and aren't subject to domain policies set by Google Apps administrators. For example, a policy set in the Google Apps admin console to restrict the ability of Apps end users to share documents outside of the domain would not apply to service accounts.
This document describes how an application can complete the server-to-server OAuth 2.0 flow by using the Google APIs Client Library for Ruby.
## Overview
To support server-to-server interactions, first create a service account for your project in the API Console. If you want to access user data for users in your Google Apps domain, then delegate domain-wide access to the service account.
Then, your application prepares to make authorized API calls by using the service account's credentials to request an access token from the OAuth 2.0 auth server.
Finally, your application can use the access token to call Google APIs.
## Creating a service account
A service account's credentials include a generated email address that is unique, a client ID, and at least one public/private key pair.
If your application runs on Google App Engine, a service account is set up automatically when you create your project.
If your application runs on Google Compute Engine, a service account is also set up automatically when you create your project, but you must specify the scopes that your application needs access to when you create a Google Compute Engine instance. For more information, see [Preparing an instance to use service accounts](https://cloud.google.com/compute/docs/authentication#using).
If your application doesn't run on Google App Engine or Google Compute Engine, you must obtain these credentials in the Google API Console. To generate service-account credentials, or to view the public credentials that you've already generated, do the following:
1. Open the [**Service accounts** page](https://console.developers.google.com/permissions/serviceaccounts). If prompted, select a project.
1. Click **Create service account**.
1. In the **Create service account** window, type a name for the service account, and select **Furnish a new private key**. If you want to [grant G Suite domain-wide authority](https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority) to the service account, also select **Enable G Suite Domain-wide Delegation**. Then click **Create**.
Your new public/private key pair is generated and downloaded to your machine; it serves as the only copy of this key. You are responsible for storing it securely.
You can return to the [API Console](https://console.developers.google.com/) at any time to view the client ID, email address, and public key fingerprints, or to generate additional public/private key pairs. For more details about service account credentials in the API Console, see [Service accounts](https://developers.google.com/console/help/service-accounts) in the API Console help file.
Take note of the service account's email address and store the service account's private key file in a location accessible to your application. Your application needs them to make authorized API calls.
> **Note:** You must store and manage private keys securely in both development and production environments. Google does not keep a copy of your private keys, only your public keys.
## Delegating domain-wide authority to the service account
If your application runs in a Google Apps domain and accesses user data, the service account that you created needs to be granted access to the user data that you want to access.
The following steps must be performed by an administrator of the Google Apps domain:
1. Go to your Google Apps domains [Admin console](http://admin.google.com/).
1. Select **Security** from the list of controls. If you don't see **Security** listed, select **More controls** from the gray bar at the bottom of the page, then select **Security** from the list of controls. If you can't see the controls, make sure you're signed in as an administrator for the domain.
1. Select **Advanced settings** from the list of options.
1. Select **Manage third party OAuth Client access** in the **Authentication** section.
1. In the **Client name** field enter the service account's **Client ID**.
1. In the **One or More API Scopes** field enter the list of scopes that your application should be granted access to. For example, if your application needs domain-wide access to the Google Drive API and the Google Calendar API, enter: `https://www.googleapis.com/auth/drive`, `https://www.googleapis.com/auth/calendar`.
1. Click **Authorize**.
Your application now has the authority to make API calls as users in your domain (to "impersonate" users). When you prepare to make authorized API calls, you specify the user to impersonate.
## Preparing to make an authorized API call
After you obtain the client email address and private key from the API Console, complete the following steps:
1. Create a Client object from the service account's credentials and the scopes your application needs access to. For example:
```rb
require 'googleauth'
require 'google/apis/compute_v1'
compute = Google::Apis::ComputeV1::ComputeService.new
# Get the environment configured authorization
scopes = ['https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/compute']
compute.authorization = Google::Auth.get_application_default(scopes)
```
If you have delegated domain-wide access to the service account and you want to impersonate a user account, specify the email address of the user account in the :sub parameter. For example:
```rb
require 'googleauth'
require 'google/apis/sqladmin_v1beta4'
# Get the environment configured authorization
scopes = ['https://www.googleapis.com/auth/sqlservice.admin']
authorization = Google::Auth.get_application_default(scopes)
# Clone and set the subject
auth_client = authorization.dup
auth_client.sub = 'user@example.org'
```
2. Use the fetch_access_token! method of the client object to acquire an access token. For example:
`auth_client.fetch_access_token!`
Use the authorized Client object to call Google APIs in your application.
## Calling Google APIs
Use the authorized Client object to call Google APIs by completing the following steps:
1. Build a service object for the API that you want to call. You build a a service object by calling the discovered_api method of an APIClient object with the name and version of the API. For example, to call version 1beta3 of the Cloud SQL Administration API:
```rb
sqladmin = Google::Apis::SqladminV1beta4::SqladminService.new
sqladmin.authorization = auth_client
Make requests to the API service using the
interface
provided by the service object, and providing the authorized
Client object. For example, to list the instances of Cloud SQL
databases in the examinable-example-123 project:
instances = sqladmin.list_instances('examinable-example-123')
```
## Complete example
The following example prints a JSON-formatted list of Cloud SQL instances in a project.
```rb
require 'googleauth'
require 'google/apis/sqladmin_v1beta4'
sqladmin = Google::Apis::SqladminV1beta4::SqladminService.new
# Get the environment configured authorization
scopes = ['https://www.googleapis.com/auth/sqlservice.admin']
sqladmin.authorization = Google::Auth.get_application_default(scopes)
instances = sqladmin.list_instances('examinable-example-123')
puts instances.to_h
```

54
docs/oauth-web.md Normal file
View File

@ -0,0 +1,54 @@
# Using OAuth 2.0 for Web Server Applications
This document explains how web server applications use the Google API Client Library for Ruby to implement OAuth 2.0 authorization to access Google APIs. OAuth 2.0 allows users to share specific data with an application while keeping their usernames, passwords, and other information private. For example, an application can use OAuth 2.0 to obtain permission from users to store files in their Google Drives.
This OAuth 2.0 flow is specifically for user authorization. It is designed for applications that can store confidential information and maintain state. A properly authorized web server application can access an API while the user interacts with the application or after the user has left the application.
Web server applications frequently also use [service accounts](service-accounts.md) to authorize API requests, particularly when calling Cloud APIs to access project-based data rather than user-specific data. Web server applications can use service accounts in conjunction with user authorization.
## Prerequisites
### Enable APIs for your project
Any application that calls Google APIs needs to enable those APIs in the API Console. To enable the appropriate APIs for your project:
1. Open the [Library](https://console.developers.google.com/apis/library) page in the API Console.
1. Select the project associated with your application. Create a project if you do not have one already.
1. Use the **Library** page to find each API that your application will use. Click on each API and enable it for your project.
### Create authorization credentials
Any application that uses OAuth 2.0 to access Google APIs must have authorization credentials that identify the application to Google's OAuth 2.0 server. The following steps explain how to create credentials for your project. Your applications can then use the credentials to access APIs that you have enabled for that project.
<ol>
<li>Open the <a href="https://console.developers.google.com/apis/credentials">Credentials page</a> in the API Console.</li>
<li>Click <b>Create credentials &gt; OAuth client ID</b>.</li>
<li>Complete the form. Set the application type to <code>Web
application</code>. Applications that use languages and frameworks
like PHP, Java, Python, Ruby, and .NET must specify authorized
<b>redirect URIs</b>. The redirect URIs are the endpoints to which the
OAuth 2.0 server can send responses.<br><br>
For testing, you can specify URIs that refer to the local machine,
such as <code>http://localhost:8080</code>. With that in mind, please
note that all of the examples in this document use
<code>http://localhost:8080</code> as the redirect URI.
<br><br>
We recommend that you <a href="#protectauthcode">design your app's auth
endpoints</a> so that your application does not expose authorization
codes to other resources on the page.</li>
</ol>
After creating your credentials, download the **client_secret.json** file from the API Console. Securely store the file in a location that only your application can access.
> **Important:** Do not store the **client_secret.json** file in a publicly-accessible location. In addition, if you share the source code to your application—for example, on GitHub—store the **client_secret.json** file outside of your source tree to avoid inadvertently sharing your client credentials.
### Identify access scopes
Scopes enable your application to only request access to the resources that it needs while also enabling users to control the amount of access that they grant to your application. Thus, there may be an inverse relationship between the number of scopes requested and the likelihood of obtaining user consent.
Before you start implementing OAuth 2.0 authorization, we recommend that you identify the scopes that your app will need permission to access.
We also recommend that your application request access to authorization scopes via an incremental authorization process, in which your application requests access to user data in context. This best practice helps users to more easily understand why your application needs the access it is requesting.
The [OAuth 2.0 API Scopes document](https://developers.google.com/identity/protocols/googlescopes) contains a full list of scopes that you might use to access Google APIs.

268
docs/oauth.md Normal file
View File

@ -0,0 +1,268 @@
# OAuth 2.0
This document describes OAuth 2.0, when to use it, how to acquire client IDs and client secrets, and generally how to use OAuth 2.0 with the Google API Client Library for Ruby.
## About OAuth 2.0
OAuth 2.0 is the authorization protocol used by Google APIs. It is summarized on the Authentication page of this library's documentation, and there are other good references as well:
- [The OAuth 2.0 Authorization Protocol](https://tools.ietf.org/html/rfc6749)
- [Using OAuth 2.0 to Access Google APIs](https://developers.google.com/identity/protocols/OAuth2)
## Acquiring client IDs and secrets
To find your project's client ID and client secret, do the following:
Select an existing OAuth 2.0 credential or open the Credentials page.
If you haven't done so already, create your project's OAuth 2.0 credentials by clicking Create credentials > OAuth client ID, and providing the information needed to create the credentials.
Look for the Client ID in the OAuth 2.0 client IDs section. For details, click the client ID.
There are different types of client IDs, so be sure to get the correct type for your application:
* Web application client IDs
* Installed application client IDs
* [Service Account](https://developers.google.com/accounts/docs/OAuth2ServiceAccount) client IDs
**Warning**: Keep your client secret private. If someone obtains your client secret, they could use it to consume your quota, incur charges against your Google APIs Console project, and request access to user data.
## The Signet library
The [Signet](https://github.com/googleapis/signet) library is included with the Google API Client Library for Ruby. It handles all steps of the OAuth 2.0 protocol required for making API calls. It is available as a separate gem if you only need an OAuth 2.0 library.
## Flows
There are three main OAuth 2.0 flows in the Google API Client Library for Ruby: web server, installed application and service account.
## Web server
We start by retrieving the client ID and client secret from a preconfigured client_secrets.json file:
```rb
client_secrets = Google::APIClient::ClientSecrets.load
```
For web-based applications, we then redirect the user to an authorization page:
```rb
# Request authorization
redirect user_credentials.authorization_uri.to_s, 303
```
The user completes the steps on her browser, and control gets returned to the application via the callback URL:
```rb
get '/oauth2callback' do
# Exchange token
user_credentials.code = params[:code] if params[:code]
user_credentials.fetch_access_token!
redirect to('/')
end
```
user_credentials now has everything needed to make authenticated requests:
```rb
events = calendar.list_events('primary', options: { authorization: user_credentials })
```
Below is the full sample we've been looking at.
```rb
require 'google/apis/calendar_v3'
require 'google/api_client/client_secrets'
require 'sinatra'
require 'logger'
enable :sessions
def logger; settings.logger end
def calendar; settings.calendar; end
def user_credentials
# Build a per-request oauth credential based on token stored in session
# which allows us to use a shared API client.
@authorization ||= (
auth = settings.authorization.dup
auth.redirect_uri = to('/oauth2callback')
auth.update_token!(session)
auth
)
end
configure do
log_file = File.open('calendar.log', 'a+')
log_file.sync = true
logger = Logger.new(log_file)
logger.level = Logger::DEBUG
Google::Apis::ClientOptions.default.application_name = 'Ruby Calendar sample'
Google::Apis::ClientOptions.default.application_version = '1.0.0'
calendar_api = Google::Apis::CalendarV3::CalendarService.new
client_secrets = Google::APIClient::ClientSecrets.load
authorization = client_secrets.to_authorization
authorization.scope = 'https://www.googleapis.com/auth/calendar'
set :authorization, authorization
set :logger, logger
set :calendar, calendar_api
end
before do
# Ensure user has authorized the app
unless user_credentials.access_token || request.path_info =~ /^\/oauth2/
redirect to('/oauth2authorize')
end
end
after do
# Serialize the access/refresh token to the session and credential store.
session[:access_token] = user_credentials.access_token
session[:refresh_token] = user_credentials.refresh_token
session[:expires_in] = user_credentials.expires_in
session[:issued_at] = user_credentials.issued_at
end
get '/oauth2authorize' do
# Request authorization
redirect user_credentials.authorization_uri.to_s, 303
end
get '/oauth2callback' do
# Exchange token
user_credentials.code = params[:code] if params[:code]
user_credentials.fetch_access_token!
redirect to('/')
end
get '/' do
# Fetch list of events on the user's default calandar
events = calendar.list_events('primary', options: { authorization: user_credentials })
[200, {'Content-Type' => 'application/json'}, events.to_h.to_json]
end
```
### Installed application
We start by retrieving the client ID and client secret from a preconfigured client_secrets.json file:
```rb
client_secrets = Google::APIClient::ClientSecrets.load
```
For installed applications, we can use the Google::APIClient::InstalledAppFlow helper class to handle most of the setup:
```rb
flow = Google::APIClient::InstalledAppFlow.new(
:client_id => client_secrets.client_id,
:client_secret => client_secrets.client_secret,
:scope => ['https://www.googleapis.com/auth/adsense.readonly']
)
```
The user completes the steps on her browser, which is opened automatically, and the authorization code is fed into the application automatically, so all it takes is:
```rb
adsense.authorization = flow.authorize(storage)
```
The client now has everything needed to make an authenticated request:
```rb
report = adsense.generate_report(start_date: '2011-01-01', end_date: '2011-08-31',
metric: %w(PAGE_VIEWS AD_REQUESTS AD_REQUESTS_COVERAGE
CLICKS AD_REQUESTS_CTR COST_PER_CLICK
AD_REQUESTS_RPM EARNINGS),
dimension: %w(DATE),
sort: %w(+DATE))
```
Below is the full sample we've been looking at.
```rb
# AdSense Management API command-line sample.
require 'google/apis/adsense_v1_4'
require 'google/api_client/client_secrets'
require 'google/api_client/auth/installed_app'
require 'google/api_client/auth/storage'
require 'google/api_client/auth/storages/file_store'
require 'logger'
require 'json'
CREDENTIAL_STORE_FILE = "#{$0}-oauth2.json"
# Handles authentication and loading of the API.
def setup
log_file = File.open('adsense.log', 'a+')
log_file.sync = true
logger = Logger.new(log_file)
logger.level = Logger::DEBUG
adsense = Google::Apis::AdsenseV1_4::AdSenseService.new
# Stores auth credentials in a file, so they survive multiple runs
# of the application. This avoids prompting the user for authorization every
# time the access token expires, by remembering the refresh token.
# Note: FileStorage is not suitable for multi-user applications.
storage = Google::APIClient::Storage.new(
Google::APIClient::FileStore.new(CREDENTIAL_STORE_FILE))
adsense.authorization = storage.authorize
if storage.authorization.nil?
client_secrets = Google::APIClient::ClientSecrets.load
# The InstalledAppFlow is a helper class to handle the OAuth 2.0 installed
# application flow, which ties in with Stroage to store credentials
# between runs.
flow = Google::APIClient::InstalledAppFlow.new(
:client_id => client_secrets.client_id,
:client_secret => client_secrets.client_secret,
:scope => ['https://www.googleapis.com/auth/adsense.readonly']
)
adsense.authorization = flow.authorize(storage)
end
return adsense
end
# Generates a report for the default account.
def generate_report(adsense)
report = adsense.generate_report(start_date: '2011-01-01', end_date: '2011-08-31',
metric: %w(PAGE_VIEWS AD_REQUESTS AD_REQUESTS_COVERAGE
CLICKS AD_REQUESTS_CTR COST_PER_CLICK
AD_REQUESTS_RPM EARNINGS),
dimension: %w(DATE),
sort: %w(+DATE))
# Display headers.
report.headers.each do |header|
print '%25s' % header.name
end
puts
# Display results.
report.rows.each do |row|
row.each do |column|
print '%25s' % column
end
puts
end
end
if __FILE__ == $0
adsense = setup()
generate_report(adsense)
end
```
## Service accounts
For server-to-server interactions, like those between a web application and Google Cloud Storage, Prediction, or BigQuery APIs, you can use service accounts.
```rb
require 'googleauth'
require 'google/apis/compute_v1'
compute = Google::Apis::ComputeV1::ComputeService.new
# Get the environment configured authorization
scopes = ['https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/compute']
compute.authorization = Google::Auth.get_application_default(scopes)
```

29
docs/pagination.md Normal file
View File

@ -0,0 +1,29 @@
# Pagination
Some API methods may return very large lists of data. To reduce the response size, many of these API methods support pagination. With paginated results, your application can iteratively request and process large lists one page at a time. When using API methods that support pagination, responses will come back with a next_page property, which builds a request for the next page for you.
To process the first page of results, construct a request as you normally would. There's usually an API-level parameter you can provide to specify the maximum size of each page, so be sure to check the API's documentation.
`stamps = service.list_stamps(cents: 5, max_results: 20)`
For further pages, repeat the request including the next page token from the previous result.
`stamps = service.list_stamps(cents:5, max_results: 20, page_token: stamps.next_page_token)`
Here is a full example which loops through the paginated results of a user's public Google Plus activities feed:
```rb
require 'google/apis/plus_v1'
plus = Google::Apis::PlusV1::PlusService.new
plus.key = '...' # API Key from the Google Developers Console
next_page = nil
begin
puts "Fetching page of activities"
activities = plus.list_activities('103354693083460731603', 'public', page_token: next_page)
activities.items.each do |activity|
puts "#{activity.published} #{activity.title}"
end
next_page = activities.next_page_token
end while next_page
```

25
docs/performance.md Normal file
View File

@ -0,0 +1,25 @@
# Performance Tips
This document covers techniques you can use to improve the performance of your application. The documentation for the specific API you are using should have a similar page with more detail on some of these topics. For example, see the Performance Tips page for the Google Drive API.
## Partial response (fields parameter)
By default, the server sends back the full representation of a resource after processing requests. For better performance, you can ask the server to send only the fields you really need and get a partial response instead.
To request a partial response, add the standard fields parameter to any API method. The value of this parameter specifies the fields you want returned. You can use this parameter with any request that returns response data.
In the following code snippet, the list_stamps method of a fictitious Stamps API is called. The cents parameter is defined by the API to only return stamps with the given value. The value of the fields parameter is set to 'count,items/name'code>. The response will only contain stamps whose value is 5 cents, and the data returned will only include the number of stamps found along with the stamp names:
`response = service.list_stamps(cents: 5, fields: 'count,items/name')`
Note how commas are used to delimit the desired fields, and slashes are used to indicate fields that are contained in parent fields. There are other formatting options for the fields parameter, and you should see the "Performance Tips" page in the documentation for the API you are using.
## Partial update (patch)
If the API you are calling supports patch, you can avoid sending unnecessary data when modifying resources. For these APIs, you can call the patch() method and supply the arguments you wish to modify for the resource. If supported, the API's reference will have documentation for the patch() method.
For more information about patch semantics, see the "Performance Tips" page in the documentation for the API you are using.
## Batch
If you are sending many small requests you may benefit from batching, which allows those requests to be bundled into a single HTTP request.