提交 a24ebdff 编写于 作者: G Grant Timmerman

Adds Docs to repo. Fixes #528, fixes #529, fixes #530, fixes #531, fixes #532,...

Adds Docs to repo. Fixes #528, fixes #529, fixes #530, fixes #531, fixes #532, fixes #533, fixes #534, fixes #535, fixes #536, fixes #537
上级 1b203129
......@@ -2,7 +2,8 @@
## Description
Written by Google, this compact and efficient client library provides access to Google REST APIs.
The Google API Client Library for JavaScript is designed for JavaScript client-application
developers. It offers simple, flexible access to many Google APIs.
> Note: This repo does not contain the source code for the `gapi` client.
......@@ -12,12 +13,20 @@ The JavaScript client library [supports these Google APIs](https://developers.go
The library supports [OAuth 2 authentication](https://developers.google.com/api-client-library/javascript/features/authentication).
## Documentation
- [Getting Started](https://developers.google.com/api-client-library/javascript/start/start-js)
- [Reference Docs](https://developers.google.com/api-client-library/javascript/reference/referencedocs)
- [Samples](https://developers.google.com/api-client-library/javascript/samples/samples)
- [Support](https://developers.google.com/api-client-library/javascript/help/support)
# Documentation
- [Getting Started](docs/start.md)
- [Reference](docs/reference.md)
## Guides
- [Auth](docs/auth.md)
- [Batch](docs/batch.md)
- [CORS](docs/cors.md)
- [Discovery Documents](docs/discovery.md)
- [FAQ](docs/faq.md)
- [Promises](docs/promises.md)
- [Samples](docs/samples.md)
## Links
......
# Google API Client LIbrary for Javascript Docs
The Google API Client Library for JavaScript is designed for JavaScript
client-application developers. It offers simple, flexible
access to many Google APIs.
# Documentation
- [Getting Started](start.md)
- [Auth](auth.md)
- [Batch](batch.md)
- [CORS](cors.md)
- [Discovery Documents](discovery.md)
- [FAQ](faq.md)
- [Promises](promises.md)
- [Reference](reference.md)
- [Samples](samples.md)
\ No newline at end of file
# Authentication
[](#top_of_page)Overview
------------------------
To access a user's private data, your application must work with Google's policies for authentication and authorization.
Google defines two levels of API access:
<table>
<tr>
<th>
Level
</th>
<th>
Description
</th>
<th>
Requires:
</th>
</tr>
<tr>
<td>
Simple
</td>
<td>
API calls do not access any private user data
</td>
<td>
API key
</td>
</tr>
<tr>
<td>
Authorized
</td>
<td>
API calls can read and write private user data, or the
application's own data
</td>
<td>
API key plus OAuth 2.0 credentials (different for
different application types)
</td>
</tr>
</table>
[](#top_of_page)Getting access keys for your application
--------------------------------------------------------
To get access keys, go to the [Google Developers Console](https://console.developers.google.com) and specify your application's name and the Google APIs it will access. For simple access, Google generates an API key that uniquely identifies your application in its transactions with the Google Auth server.
For authorized access, you must also tell Google your website's protocol and domain. In return, Google generates a client ID. Your application submits this to the Google Auth server to get an OAuth 2.0 access token.
For detailed instructions for this process, see the [Getting started](https://developers.google.com/api-client-library/javascript/start/start-js) page.
See below for details and examples of how to use these credentials in your application.
[](#top_of_page)Simple access using the API key
-----------------------------------------------
The API key identifies your application for requests that don't require authorization.
Whether or not your application requires authorized access, your code should call `gapi.client.init` with the `apiKey` parameter.
```js
gapi.client.init({ 'apiKey': 'YOUR\_API\_KEY', ...
}).then(...)
```
For a complete example of simple API access, follow [this link](https://developers.google.com/api-client-library/javascript/samples/samples#LoadinganAPIandMakingaRequest).
[](#top_of_page)Authorized access
---------------------------------
To access a user's personal information, your application must work with Google's OAuth 2.0 mechanism.
### OAuth 2.0 basics
You may want to start with this overview of [Using OAuth 2.0 to Access Google APIs](https://developers.google.com/accounts/docs/OAuth2).
Behind the scenes, the OAuth 2.0 mechanism performs a complex operation to authenticate the user, the application, and the Google Auth server. The components of the JavaScript client library manage this process for you, so that all your code has to do is pass in the following objects:
* The client ID you received when you registered your application
* The scope object that specifies which data your application will use
### About scope
The scope object defines the level of access to a particular API that your application will use. For more information about how scopes work, refer to [this OAuth 2.0 documentation](https://developers.google.com/accounts/docs/OAuth2.html). The scope is a **space delimited string**. The following example represents read-only access to a user's Google Drive:
https://www.googleapis.com/auth/drive.readonly
### OAuth 2.0 authorization flow
The JavaScript client library uses the [OAuth 2.0 client-side flow](https://developers.google.com/accounts/docs/OAuth2UserAgent) for making requests that require authorization. If you would like to see what this looks like in action, check out [Google's OAuth 2.0 Playground](https://developers.google.com/oauthplayground/).
OAuth 2.0 authorization in the JavaScript client library proceeds as follows:
1. The user clicks a "login" link.
2. The browser shows a popup that allows the user to authenticate and authorize the web application.
3. After successful authorization, the browser redirects the user back to the calling application (your application).
4. The callback saves the authorization token and closes the popup.
After this, the user is signed in to your application, and the application is authorized to access the user's personal data. The user's sign-in state is persistent across sessions, so the next time the user opens your application, the user is automatically signed in.
[](#top_of_page)Auth example
----------------------------
See the [auth example](https://developers.google.com/api-client-library/javascript/samples/samples#authorizing-and-making-authorized-requests) on the Samples page.
[](#top_of_page)Making a request with CORS
------------------------------------------
To make an authenticated [CORS](http://www.w3.org/TR/cors/) request, you can add the OAuth 2.0 access token to the request header or add it as a URL parameter. For details, read the [CORS documentation](https://developers.google.com/api-client-library/javascript/features/cors).
[](#top_of_page)The standalone auth client
------------------------------------------
Your application can also use a subset of the full JavaScript client library that performs authentication and nothing else. It includes only the `gapi.auth` methods.
Use the standalone auth client in web applications that will run in environments with full CORS support, such as Chrome extensions and mobile browsers. If your application may run on browsers which do not support CORS, or if you want to use other features of the JavaScript library, use the standard JavaScript client.
For information about how to load and use the auth client, see the [CORS documentation](https://developers.google.com/api-client-library/javascript/features/cors).
\ No newline at end of file
# Making Batch Requests
The JavaScript client library supports batching HTTP requests to make multiple API calls in one round-trip. For reference documentation about batch-related methods and classes, see [Methods and Classes](/api-client-library/javascript/reference/referencedocs)
## Creating a batch
The JavaScript client library defines an object called `Batch`. You can start by instantiating this object:
```js
var batch = gapi.client.newBatch();
```
## Adding requests to the batch
Use the `Batch` object's [`add`](/api-client-library/javascript/reference/referencedocs#gapiclientBatchadd) method to add individual HTTP requests. The `add` method supports one optional parameter:
<table>
<colgroup>
<col style="width:25%" />
<col style="width:10%" />
<col style="width:65%" />
</colgroup>
<tr>
<th>
Param
</th>
<th>
Type
</th>
<th>
Description
</th>
</tr>
<tr>
<td>
<code>id</code>
</td>
<td>
string
</td>
<td>
If an ID is supplied, the API attaches it to the
response to this request. If no ID is supplied, the API
generates a random ID.
</td>
</tr>
</table>
Example:
```js
var searchRequest = function(name) {
return gapi.client.request({
'path': 'plus/v1/people',
'params': {'query': name}
});
};
var searchAlvin = searchRequest('Alvin');
var searchSimon = searchRequest('Simon');
// Adding just the request
batch.add(searchAlvin);
// Adding the request with an ID
batch.add(searchSimon, {'id': 'searchSimon'});
```
## Executing a batch
Batch requests are executed just like individual requests, using [`gapi.client.Batch.then`](/api-client-library/javascript/reference/referencedocs#gapiclientBatchthen).
### Batch request promise
If the batch promise is fulfilled, the result field of the response will contain a batch response map. This map contains the responses to all requests in the batch, keyed by the ID of the request (either user-supplied or generated randomly by the client). The value is the API's response as a parsed JSON object.
### Individual request promises
Each request in the batch can also be treated as a promise. If the `then` method is invoked on an individual request, the promise will be fulfilled or rejected with a value, just as if the request had been executed individually.
For more information about the response formats and using batch promises, see the [Using Promises](/api-client-library/javascript/features/promises) section.
\ No newline at end of file
# How to use CORS to access Google APIs
Google APIs support requests and responses using [Cross-origin Resource Sharing](http://www.w3.org/TR/cors/) (CORS). You do not need to load the complete JavaScript client library to use CORS. If you want your application to access a user's personal information, however, it must still work with Google's OAuth 2.0 mechanism. To make this possible, Google provides the standalone auth client — a subset of the JavaScript client.
This page explains how to use the standalone auth client and CORS to access Google APIs.
Loading the standalone auth client
----------------------------------
The standalone Auth client can be loaded with the JavaScript client's `load` function:
```html
<script src="https://apis.google.com/js/api.js" type="text/javascript"></script>
<script type="text/javascript">
gapi.load('auth2', function() {
// Library loaded.
});
</script>
```
Using CORS
----------
To start, you may want to check out this excellent HTML 5 Rocks [tutorial](http://www.html5rocks.com/en/tutorials/cors/) for an overview on how to use CORS.
Use [XMLHttpRequest2](http://www.w3.org/TR/XMLHttpRequest/) to make CORS requests.
**Note:** The examples in this documentation use the `XMLHttpRequest` constructor. Please be sure to check [browser compatibility](http://caniuse.com/#search=cors) for all the browsers you want to support. For cross-browser compatibility, use a helper function such as `createCORSRequest` from the tutorial linked to above.
A CORS request to a Google API is similar to a [REST](/api-client-library/javascript/reference/referencedocs#gapiclientrequest) request. The URL for a CORS request follows this pattern:
```
https://www.googleapis.com +
REST path + URL Params
```
**Example:** here is a REST request:
```js
var restRequest = gapi.client.request({
'path': 'https://people.googleapis.com/v1/people/me/connections',
'params': {'sortOrder': 'LAST_NAME_ASCENDING'}
});
```
And here is the equivalent CORS request:
```js
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://people.googleapis.com/v1/people/me/connections?sortOrder=LAST_NAME_ASCENDING');
```
Request headers are added to the request using [XMLHttpRequest.setRequestHeader](http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method).
The request body is sent using the [XMLHttpRequest.send](http://www.w3.org/TR/XMLHttpRequest/#the-send-method) method.
You can register callbacks by adding event listeners on the `load` and `error` events.
Follow this link for information about [XMLHttpRequest events](http://www.w3.org/TR/XMLHttpRequest/#events)
Making authenticated requests
-----------------------------
To obtain an access token for making authenticated requests, use the same `gapi.auth2` methods from the standard JavaScript Client or the auth-only client. For instructions on obtaining an access token, see the [Authentication page](/api-client-library/javascript/features/authentication). There are two ways to make an authenticated request with CORS:
* Send the access token in the Authorization [request header](http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader-method).
* Include the access token as the `access_token` parameter in the URL.
To retrieve an access token, call the `getAuthResponse()` method of a `GoogleUser` object.
The format of the [OAuth 2.0 token](/api-client-library/javascript/reference/referencedocs#OAuth20TokenObject) is described in the [Methods and classes](/api-client-library/javascript/reference/referencedocs) document.
### Example 1: Using the request header
```js
var user = gapi.auth2.getAuthInstance().currentUser.get();
var oauthToken = user.getAuthResponse().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET',
'https://people.googleapis.com/v1/people/me/connections');
xhr.setRequestHeader('Authorization',
'Bearer ' + oauthToken);
xhr.send();
```
### Example 2: Using the URL parameter
```js
var user = gapi.auth2.getAuthInstance().currentUser.get();
var oauthToken = user.getAuthResponse().access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET',
'https://people.googleapis.com/v1/people/me/connections' +
'?access_token=' + encodeURIComponent(oauthToken));
xhr.send();
```
\ No newline at end of file
# API Discovery Document
An API Discovery document describes the surface for a particular version of an API. The information includes API name, API version, API description, resource schemas, method definitions, authentication requirements, and more. The JavaScript client library uses the information to generate corresponding JavaScript methods that applications can use.
## Finding an API's Discovery Document URL
If an API explicitly documents its discovery URL, always use it as-is to load the JavaScript client library. For example, the [People API](https://developers.google.com/people/api/rest/) documents its discovery URL as:
https://people.googleapis.com/$discovery/rest?version=v1
Use this URL to load your JavaScript client.
If there's no discovery URL in the API's documentation, you can construct the default discovery URL using the API name and the API version as follows:
https://www.googleapis.com/discovery/v1/apis/name/version/rest
For example, the Discovery URL of [Translate API v2](https://cloud.google.com/translate/v2/quickstart) is:
https://www.googleapis.com/discovery/v1/apis/translate/v2/rest
See [Google API Discovery Service](https://developers.google.com/discovery/v1/getting_started#REST) for details.
## Discovering generated methods
After loading an API Discovery Document, the JavaScript client library automatically generates JavaScript methods for interacting with the API. For each method defined in the API Discovery Document, a corresponding method is constructed on the `gapi.client` object. For example, The [People API](https://developers.google.com/people/api/rest/)'s methods are under `gapi.client.people`. The People API has the methods `people.get` and `people.connections.list`, the generated methods can be called as follows:
`gapi.client.people.people.get(...)`
`gapi.client.people.people.connections.list(...)`
You can view API methods on [APIs Explorer](https://developers.google.com/apis-explorer/). Alternatively, you can view the generated methods interactively in a browser's console (such as by using the Inspect command in Chrome) by printing the generated object `console.log(gapi.client.people)`.
\ No newline at end of file
# FAQ
### Can I use the JavaScript client library to work with local files, using the `file://` protocol?
The JavaScript client library does not support local pages and the `file://` protocol. The application must be hosted on a server (can be localhost).
### Does the JavaScript client library set authentication cookies?
The JavaScript client library does not write any auth cookies. `gapi.auth.getToken` and `gapi.auth.setToken` provide access to the auth token.
### How do I refresh the auth token, and how often should I do it?
Refresh the token by calling `gapi.auth.authorize` with the client ID, the scope and `immediate:true` as parameters.
Currently, the auth token expires after one hour. A common practice is to refresh the auth token after 45 minutes. If you refresh the auth token too often (every five minutes, for example) you will run into the refresh rate limit. (The rate limit is per-user, so the number of user connections is not an issue.)
The auth token's `expires_in` field will tell you the token's time to expiration.
The [authSample.html file](https://github.com/google/google-api-javascript-client/blob/master/samples/authSample.html) contains good examples of code that handles auth and token refreshes.
### Is it possible to use the JavaScript client library in an installed application?
At this time, the JavaScript client library supports web applications only. For mobile devices you can use one of our other client libraries like the one for [Objective-C](http://code.google.com/p/google-api-objectivec-client/)
### How can I use the JavaScript client library to log the user out of my application?
The JavaScript client library does not directly support logging the user out of the application. Typically, developers include a logout link to https://accounts.google.com/logout.
Since logging out of the application also logs the user out of the Google account, it is not recommended to log the user out unless the user requests this explicitly.
For a workaround that allows your application to log the user out programatically, see [this topic](https://groups.google.com/forum/?fromgroups=#!topic/google-api-javascript-client/PCs8xXV4wxk) in the JavaScript client library discussion group.
\ No newline at end of file
# Using Promises
A JavaScript _promise_ represents the result of an asynchronous operation. Promises can be in one of three states, pending, fulfilled, or rejected. To access a promise's fulfilled value or rejection reason, register your handler to the promise's `then` method.
The JavaScript client library provides a [Promises/A+](http://promisesaplus.com/)\-conformant interface. We strongly recommend that you use promises instead of callbacks. Requests made using the promise interface are RESTful. Using promises also gives you elegant error handling and easy chaining, and the Google JavaScript promise interface fixes various small bugs and inconsistencies that were present in the older callback-based interface.
Using promises
--------------
Requests created through `gapi.client.request`, `gapi.client.newBatch`, and registered API methods are "thenable." `gapi.client.load` also returns a promise if a callback argument is not provided. Each of the requests has a `then(opt_onFulfilled, opt_onRejected, opt_context)` method that takes three optional parameters:
<table>
<colgroup>
<col style="width:25%" />
<col style="width:10%" />
<col style="width:65%" />
</colgroup>
<tr>
<th>
Parameter
</th>
<th>
Type
</th>
<th>
Description
</th>
</tr>
<tr>
<td>
<code>opt_onFulfilled(response)</code>
</td>
<td>
function
</td>
<td>
Optional fulfilled promise handler.
</td>
</tr>
<tr>
<td>
<code>opt_onRejected(reason)</code>
</td>
<td>
function
</td>
<td>
Optional rejected promise handler.
</td>
</tr>
<tr>
<td>
<code>opt_context</code>
</td>
<td>
object
</td>
<td>
Optional context for the handlers to execute in.
</td>
</tr>
</table>
**Note:** The promises in this library are resolved _lazily_. That means that no network requests are actually made until `then` is invoked. Once a promise is resolved or rejected with a value, the value does not change.
**Note:** We strongly recommended that you always provide a rejection handler. Rejections that your code does not handle are propagated as top-level exceptions. Rejection reasons can include application-level errors and network errors.
Fulfilled responses and application-level rejections are in the following format:
<table width="90%">
<colgroup>
<col width="10%" />
<col width="10%" />
<col width="70%" />
</colgroup>
<tr>
<th>
Name
</th>
<th>
Type
</th>
<th>
Description
</th>
</tr>
<tr>
<td style="vertical-align:top">
<code>response | reason</code>
</td>
<td style="vertical-align:top">
object
</td>
<td>
An object containing information about the HTTP response.
<table>
<colgroup>
<col width="10%" />
<col width="10%" />
<col width="80%" />
</colgroup>
<tr>
<td>
<b>Name</b>
</td>
<td>
<b>Type</b>
</td>
<td>
<b>Description</b>
</td>
</tr>
<tr>
<td>
<code><var class="apiparam">result</var></code>
</td>
<td>
*
</td>
<td>
The JSON-parsed result. <code>false</code> if not JSON-parseable.
</td>
</tr>
<tr>
<td>
<code><var class="apiparam">body</var></code>
</td>
<td>
string
</td>
<td>
The raw response string.
</td>
</tr>
<tr>
<td>
<code><var class="apiparam">headers</var></code>
</td>
<td>
object | undefined
</td>
<td>
The map of HTTP response headers.
</td>
</tr>
<tr>
<td>
<code><var class="apiparam">status</var></code>
</td>
<td>
number | undefined
</td>
<td>
HTTP status.
</td>
</tr>
<tr>
<td>
<code><var class="apiparam">statusText</var></code>
</td>
<td>
string | undefined
</td>
<td>
HTTP status text.
</td>
</tr>
</table>
</td>
</tr>
</table>
Single requests example:
```js
gapi.client.request({'path': '/plus/v1/people', 'query': 'John'}).then(function(response) {
// Handle response
}, function(reason) {
// Handle error
});
gapi.client.load('plus', 'v1').then(function() {
gapi.client.plus.people.search({'query': ''}).then(...);
});
```
### Batch requests
When you create a request with the intention of adding it to a batch, do not invoke its `then` method until after the request has been added to the batch. If the `then` method is invoked before the request is added, the request is sent immediately instead of as part of the batch. You can invoke the requests's `then` method before or after the batch's `then`. The optional `callback` parameter to the `add` method has no effect when the batch object is treated as a promise.
Example:
```js
var req1 = ... // Instantiate
var req2 = ... // Instantiate
var batch = gapi.client.newBatch();
batch.add(req1);
batch.add(req2);
req1.then(...);
batch.then(...);
req2.then(...);
```
Context parameter
Passing the context parameter is equivalent to binding the context value to the promise handlers by setting `this` in the handlers to point to the context.
Example:
```js
var personFetcher = {
results: [],
fetch: function(name) {
gapi.client.request({path: '/plus/v1/people', params:{query: name}}).then(function(response) {
this.results.push(response.result);
}, function(reason) {
console.error(name, 'was not fetched:', reason.result.error.message);
}, this);
}
};
personFetcher.fetch('John');
```
## Migrating from callbacks to promises
Migrating from callbacks to promises
------------------------------------
The `result` parameter of the fulfilled promise value is equivalent to the first parameter in [`execute`](/api-client-library/javascript/reference/referencedocs#gapiclientRequestexecute)'s callback. To update your code to use promises, change your code as shown in the before and after examples below.
The following example shows using a callback:
```js
gapi.client.request({
'path': 'plus/v1/people',
'params': {'query': name}
}).execute(function(resp, rawResp) {
processResponse(resp);
});