From 97c53e505ccd833170a6d6baf87adf770546b18c Mon Sep 17 00:00:00 2001 From: Grant Timmerman Date: Thu, 6 Jun 2019 11:42:40 -0400 Subject: [PATCH 01/28] Update README.md Simplify language. --- README.md | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 1dea5a8..2e92f65 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,9 @@ ## Description -Written by Google, this compact and efficient client library provides access to Google REST APIs. See below for a list of supported APIs. +Written by Google, this compact and efficient client library provides access to Google REST APIs. + +> Note: This repo does not contain the source code for the `gapi` client. ## Features @@ -12,13 +14,12 @@ The library supports [OAuth 2 authentication](https://developers.google.com/api- ## 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) +- [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) ## Links - - Blogs - - [Announcements](http://google-api-javascript-client.blogspot.com/) - - Groups - - [Discuss](http://groups.google.com/group/google-api-javascript-client) + +- [Discussions](https://github.com/google/google-api-javascript-client/issues) +- [Announcements](http://google-api-javascript-client.blogspot.com/) From a24ebdff3504720744483c9c0450221cac42f39d Mon Sep 17 00:00:00 2001 From: Grant Timmerman Date: Wed, 12 Jun 2019 12:39:51 -0700 Subject: [PATCH 02/28] Adds Docs to repo. Fixes #528, fixes #529, fixes #530, fixes #531, fixes #532, fixes #533, fixes #534, fixes #535, fixes #536, fixes #537 --- README.md | 23 +- docs/README.md | 17 + docs/auth.md | 123 +++++++ docs/batch.md | 79 ++++ docs/cors.md | 95 +++++ docs/discovery.md | 31 ++ docs/faq.md | 31 ++ docs/promises.md | 252 +++++++++++++ docs/reference.md | 911 ++++++++++++++++++++++++++++++++++++++++++++++ docs/samples.md | 91 +++++ docs/start.md | 146 ++++++++ 11 files changed, 1792 insertions(+), 7 deletions(-) create mode 100644 docs/README.md create mode 100644 docs/auth.md create mode 100644 docs/batch.md create mode 100644 docs/cors.md create mode 100644 docs/discovery.md create mode 100644 docs/faq.md create mode 100644 docs/promises.md create mode 100644 docs/reference.md create mode 100644 docs/samples.md create mode 100644 docs/start.md diff --git a/README.md b/README.md index 2e92f65..81c47f7 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..386d50f --- /dev/null +++ b/docs/README.md @@ -0,0 +1,17 @@ +# 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 diff --git a/docs/auth.md b/docs/auth.md new file mode 100644 index 0000000..3a127a1 --- /dev/null +++ b/docs/auth.md @@ -0,0 +1,123 @@ +# 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: + + + + + + + + + + + + + + + + + +
+ Level + + Description + + Requires: +
+ Simple + + API calls do not access any private user data + + API key +
+ Authorized + + API calls can read and write private user data, or the + application's own data + + API key plus OAuth 2.0 credentials (different for + different application types) +
+ +[](#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 diff --git a/docs/batch.md b/docs/batch.md new file mode 100644 index 0000000..88fb984 --- /dev/null +++ b/docs/batch.md @@ -0,0 +1,79 @@ +# 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: + + + + + + + + + + + + + + + + + +
+ Param + + Type + + Description +
+ id + + string + + 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. +
+ +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 diff --git a/docs/cors.md b/docs/cors.md new file mode 100644 index 0000000..494d9cb --- /dev/null +++ b/docs/cors.md @@ -0,0 +1,95 @@ +# 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 + + +``` + +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 diff --git a/docs/discovery.md b/docs/discovery.md new file mode 100644 index 0000000..64430ff --- /dev/null +++ b/docs/discovery.md @@ -0,0 +1,31 @@ +# 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 diff --git a/docs/faq.md b/docs/faq.md new file mode 100644 index 0000000..4efd28e --- /dev/null +++ b/docs/faq.md @@ -0,0 +1,31 @@ +# 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 diff --git a/docs/promises.md b/docs/promises.md new file mode 100644 index 0000000..9de1612 --- /dev/null +++ b/docs/promises.md @@ -0,0 +1,252 @@ +# 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: + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Parameter + + Type + + Description +
+ opt_onFulfilled(response) + + function + + Optional fulfilled promise handler. +
+ opt_onRejected(reason) + + function + + Optional rejected promise handler. +
+ opt_context + + object + + Optional context for the handlers to execute in. +
+ +**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: + + + + + + + + + + + + + + + + + +
+ Name + + Type + + Description +
+ response | reason + + object + + An object containing information about the HTTP response. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Name + + Type + + Description +
+ result + + * + + The JSON-parsed result. false if not JSON-parseable. +
+ body + + string + + The raw response string. +
+ headers + + object | undefined + + The map of HTTP response headers. +
+ status + + number | undefined + + HTTP status. +
+ statusText + + string | undefined + + HTTP status text. +
+
+ +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); + }); +``` + +You can rewrite the example shown above to use a promise like the following: + +```js +gapi.client.request({ + 'path': 'plus/v1/people', + 'params': {'query': name} + }).then(function(resp) { + processResponse(resp.result); + }); +``` \ No newline at end of file diff --git a/docs/reference.md b/docs/reference.md new file mode 100644 index 0000000..dd5c501 --- /dev/null +++ b/docs/reference.md @@ -0,0 +1,911 @@ +# Methods and Classes +

+ This page documents all the methods and classes defined in + the JavaScript client library. +

+

Loading the client library

+
+

+ gapi.load(libraries, callbackOrConfig) + +

+

+ Asynchronously loads the gapi libraries requested. Use this method to load the + gapi.client library. +

+

+ Arguments: +

+ + + + + + + + + + + + + + + + +
+ Name + + Type + + Description +
+ libraries + + string + + A colon (:) separated list of gapi libraries. Ex: + "client:auth2". +
+ callbackOrConfig + + function|object + + Either: +
    +
  • A callback function that is called when the libraries have finished loading.
  • +
  • + An object encapsulating the various configuration parameters for this method. Only + callback is required. + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + Name + + Type + + Description +
    + callback + + function + + The function called when the libraries have finished loading. +
    + onerror + + function + + The function called if the libraries failed to load. +
    + timeout + + number + + The number of milliseconds to wait before calling the + ontimeout function, if the libraries still haven't + loaded. +
    + ontimeout + + function + + The function called if the libraries loading has taken more time than + specified by the timeout parameter. +
    +
  • +
+
+

+ Example: +

+
gapi.load('client', {
+callback: function() {
+// Handle gapi.client initialization.
+initGapiClient();
+},
+onerror: function() {
+// Handle loading error.
+alert('gapi.client failed to load!');
+},
+timeout: 5000, // 5 seconds.
+ontimeout: function() {
+// Handle timeout.
+alert('gapi.client could not load in a timely manner!');
+}
+});
+
+

Client setup

+
+

+ gapi.client.init(args) +

+

+ Initializes the JavaScript client with API key, OAuth client ID, scope, and + API discovery document(s). + If OAuth client ID and scope are provided, this function will load the + gapi.auth2 module to perform OAuth. The gapi.client.init function + can be run multiple times, such as to set up more APIs, to change API key, or initialize + OAuth lazily. Note that the scope and clientId parameters cannot + be provided multiple times, since the gapi.auth2 module can only be initialized + once. +

+

+ Arguments: +

+ + + + + + + + + + + +
+ Name + + Type + + Description +
+ args + + object + + An object encapsulating the various arguments for this + method. Every argument is optional. + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Name + + Type + + Description +
+ apiKey + + string + + The API Key to use. +
+ discoveryDocs + + array + + An array of discovery doc URLs or discovery doc JSON objects + (Example). +
+ clientId + + string + + The app's client ID, found and created in the Google Developers Console. +
+ scope + + string + + The scopes to request, as a space-delimited string. +
+
+

+ Returns: +

+ + + + + + + + + +
+ Type + + Description +
+ + goog.Thenable + + The return value is a Promise-like + + goog.Thenable + object that resolves when all initializations, including setting the API key, loading + discovery documents, and initializing auth, are done. +
+
+ +
+

+ gapi.client.load(urlOrObject) +

+

+ Loads the client library interface to a particular API with + discovery document + URL or JSON object. Returns a Promise-like + + goog.Thenable + object that resolves when the API interface is loaded. The loaded API interface will be in + the form + gapi.client.api.collection.method. For example, the Moderator + API would create methods like + gapi.client.moderator.series.list. +

+

+ Arguments: +

+ + + + + + + + + + + +
+ Name + + Type + + Description +
+ urlOrObject + + string | object + + The Discovery Document URL or parsed Discovery Document JSON object + (Example). +
+

+ Returns: +

+ + + + + + + + + +
+ Type + + Description +
+ + goog.Thenable + + The return value is a Promise-like + + goog.Thenable object that resolves when the API interface is loaded. +
+
+ +
+

+ gapi.client.load(name, + version, + callback) +

+

+ Deprecated. Please load APIs with discovery documents. + Loads the client library interface to a particular API. If a callback is not provided, a + + goog.Thenable is returned. The loaded API interface will be in the form + gapi.client.api.collection.method. For example, the Moderator + API would create methods like + gapi.client.moderator.series.list. +

+

+ Arguments: +

+ + + + + + + + + + + + + + + + + + + + + +
+ Name + + Type + + Description +
+ name + + string + + The name of the API to load. +
+ version + + string + + The version of the API to load. +
+ callback + + function + + (optional) the function that is called once the API + interface is loaded. If not provided, a + + goog.Thenable is returned. +
+
+ +
+

+ gapi.client.setApiKey(apiKey) +

+

+ Sets the API key for the application, which can be found in + the Developer Console. Some APIs require this to be set in + order to work. +

+

+ Arguments: +

+ + + + + + + + + + + +
+ Name + + Type + + Description +
+ apiKey + + string + + The API key to set. +
+
+ +
+

+ gapi.client.setToken(tokenObject) +

+

+ Sets the authentication token to use in requests. This should be used if the token was + obtained without using the gapi.auth2 authentication library (for instance, + when using Firebase to authenticate users). +

+

+ Arguments: +

+ + + + + + + + + + + +
+ Name + + Type + + Description +
+ tokenObject + + object + + An object containing the access_token to use in API requests. + + + + + + + + + + + +
+ Name + + Type + + Description +
+ access_token + + string + + The access token granted to the user. +
+
+
+ +

API requests

+
+

+ gapi.client.request(args) +

+

+ Creates a HTTP request for making RESTful requests. +

+

+ Arguments: +

+ + + + + + + + + + + +
+ Name + + Type + + Description +
+ args + + object + + An object encapsulating the various arguments for this + method. The path is required, the rest are optional. + The values are described in detail below. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ Name + + Type + + Description +
+ path + + string + + The URL to handle the request. +
+ method + + string + + The HTTP request method to use. Default is + GET. +
+ params + + object + + URL params in key-value pair form. +
+ headers + + object + + Additional HTTP request headers. +
+ body + + string | object + + The HTTP request body (applies to PUT or POST). +
+
+

+ Returns: +

+ + + + + + + + + +
+ Type + + Description +
+ gapi.client.Request | undefined + + The returned gapi.client.Request object implements + + goog.Thenable and can be used like a Promise that + fulfills with the response object or rejects with a reason object. +
+
+
+

+ gapi.client.Request +

+

+ An object encapsulating an HTTP request. This object is not + instantiated directly, rather it is returned by gapi.client.request. + There are two ways to execute a request. We recommend that you treat the object as a promise + and use the then method, but you can also use the execute method + and pass in a callback. +

+
+
+

+ gapi.client.Request.then(onFulfilled, onRejected, context) +

+

+ For more information about using promises, see + Using Promises. +

+
+
+

+ gapi.client.Request.execute(callback) +

+

+ Executes the request and runs the supplied callback on + response. +

+

+ Arguments: +

+ + + + + + + + + + + +
+ Name + + Type + + Description +
+ callback(jsonResp,rawResp) + + function + + The callback function which executes when the request + succeeds or fails. jsonResp contains the + response parsed as JSON. If the response is not JSON, + this field will be false. + rawResp is the HTTP response. It is JSON, + and can be parsed to an object which includes + body, headers, + status, and statusText + fields. +
+
+ +

Batch API requests

+
+

+ gapi.client.newBatch() +

+

+ Creates a batch object for batching individual requests. +

+

+ Returns: +

+ + + + + + + + + +
+ Type + + Description +
+ gapi.client.Batch | undefined + + The returned gapi.client.Batch implements + + goog.Thenable interface and can be used like a Promise that fulfills with + a batch response object and rejects with a reason object. +
+
+
+

+ gapi.client.Batch +

+

+ Represents an HTTP Batch operation. Individual HTTP requests are + added with the add method and the batch can be + executed using then or execute. We recommend that you treat the + batch object as a promise and use then. This class defines the following + methods: +

+
+
+

+ gapi.client.Batch.add(request,opt_params) +

+

+ Adds a gapi.client.Request to the batch. +

+

+ Arguments: +

+ + + + + + + + + + + + + + + + +
+ Name + + Type + + Description +
+ request + + gapi.client.Request + + The HTTP request to add to this batch. This parameter is + required. +
+ opt_params + + Object + + Optional extra parameters for this batch entry. + Accepted fields are id and + callback: + + + + + + + + + + + + + + + + +
+ Name + + Type + + Description +
+ id + + string + + Identifies the response for this request in the + map of batch responses. If one is not provided, the + system generates a random ID. +
+ callback(individualResponse, + rawBatchResponse) + + function + + individualResponse is the response + for this request only. Its format is defined by + the API method being called. + rawBatchResponse is the raw batch + ID-response map as a string. It contains all + responses to all requests in the batch. +
+
+
+
+

+ gapi.client.Batch.then(onFulfilled, onRejected, context) +

+

+ For more information about using promises, see + Using Promises. +

+
+
+

+ gapi.client.Batch.execute(callback) +

+

+ Executes all requests in the batch. The supplied callback + is executed on success or failure. +

+ + + + + + + + + + + +
+ Name + + Type + + Description +
+ callback(responseMap, + rawBatchResponse) + + function + + The callback to execute when the batch returns. + responseMap is an ID-response map of each + requests response. rawBatchResponse is the + same response, but as an unparsed JSON-string. +
+
\ No newline at end of file diff --git a/docs/samples.md b/docs/samples.md new file mode 100644 index 0000000..8fc63f4 --- /dev/null +++ b/docs/samples.md @@ -0,0 +1,91 @@ +# Samples + +This page provides three detailed examples which demonstrate the library's functionality. Browse the [project source](https://code.google.com/p/google-api-javascript-client/source/browse/#hg%2Fsamples) for additional samples. + +Loading an API and Making a Request +----------------------------------- + +This snippet shows how to load an API and make a request. In this case, the request is going to Google Translate API. It's an example of "simple access", where the only credential required is the API key. + +```html + + + + + + +
+ + +``` + +## Authorizing and Making Authorized Requests + +The following sample demonstrates how to get "authorized" access to a Google API using OAuth 2.0. See the full sample at [authSample.html](https://github.com/google/google-api-javascript-client/blob/master/samples/authSample.html). + +It's called "authorized" access because the user must give the application direct authorization to use personal data. Simple web-based applications using JavaScript usually get this authorization the way this example does: by displaying button for the user to click. This action triggers a call to a Google auth server, which pops up a standard authorization dialog. For details, see the [Authentication page](/api-client-library/javascript/features/authentication). + +**Note:** Here we use `gapi.load('client:auth2', ...)` to load both the `client` module (for dealing with API requests) and the `auth2` module (for dealing with OAuth 2.0) upfront. The `gapi.client.init` fuction lazily loads `auth2` if it is needed. If you are sure your app needs auth, loading the two modules `'client:auth2'` together before you call `gapi.client.init` will save one script load request. + +To make `gapi.client.init` set up OAuth correctly, you would have to assign the `clientID` variable the client ID generated when you registered your application (again, for instructions see the [Getting Started](/api-client-library/javascript/start/start-js#Getaccesskeysforyourapplication) page). The other parameter is `scope`, which in this case is just the scope for user profile permission. + +When the user clicks **Authorize**, the `gapi.auth2.getAuthInstance().signIn()` function is called, which shows user a popup window to let user authorize. Note that the `gapi.auth2.getAuthInstance().signIn()` can be only called from a user interaction context for most browsers (i.e. do not call it when your app starts, but call it in a button click handler). + +**Note:** when you authorize your application using Oauth 2.0, you do not also need to set the API key as in the first example. However, it is a good practice to do so, in case your code ever expands to handle unauthorized requests. + +## Loading the Library Asychronously + +The following code snippet shows how to load the library without blocking UI loading. (The `onreadystatechange` is used to support old versions of IE.) + +```html + + + + + + +
+ + +``` + +## Putting it all together + +The file [authSample.html](https://github.com/google/google-api-javascript-client/blob/master/samples/authSample.html) expands on the concepts on this page and provides a more complete example of making an authenticated call to the Google People API. \ No newline at end of file diff --git a/docs/start.md b/docs/start.md new file mode 100644 index 0000000..e7ebe12 --- /dev/null +++ b/docs/start.md @@ -0,0 +1,146 @@ +# Getting Started + +You can use the JavaScript client library to interact with Google APIs, such as People, Calendar, and Drive, from your web applications. Follow the instructions on this page to get started. + +[](#top_of_page)How to make API requests +---------------------------------------- + +There are several ways to use the JavaScript client library to make API requests, but they all follow the same basic pattern: + +1. The application loads the JavaScript client library. +2. The application initializes the library with API key, OAuth client ID, and [API Discovery Document(s)](https://developers.google.com/api-client-library/javascript/features/discovery). +3. The application sends a request and processes the response. + +The following sections show 3 common ways of using the JavaScript client library. + +### Option 1: Load the API discovery document, then assemble the request. + +The following example assumes the user has already signed in. For a full example of how to sign in a user, see the [full auth sample](https://developers.google.com/api-client-library/javascript/samples/samples#authorizing-and-making-authorized-requests). + +```html + + +``` + +### Option 2: Use `gapi.client.request` + +A more general way to make requests is to use [`gapi.client.request`](https://developers.google.com/api-client-library/javascript/reference/referencedocs#gapiclientrequest). Your application does not have to load the Discovery Document as in the first option, but it must still set the API key (and auth for some APIs). While you need to manually fill in REST parameters with this option, it saves one network request and reduces application size. + +```html + + +``` + +### Option 3: Use CORS + +Google APIs support [CORS](http://www.w3.org/TR/cors/). If your application needs to do media uploads and downloads, it should use CORS. See the [CORS Support](https://developers.google.com/api-client-library/javascript/features/cors) page for details. + +[](#top_of_page)Supported environments +-------------------------------------- + +The JavaScript client library works with the same browsers supported by [Google Apps](https://support.google.com/a/answer/33864) except that mobile browsers are currently not fully supported. It only works within HTML documents with a `` element served using the `https` _(preferred)_ and `http` protocols. However, `