diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..1aed3a5 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,25 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: '' +assignees: '' + +--- + +*Important gapi.auth2 notice*: gapi.auth2 has been deprecated and replaced with Google Identity Services. Please see https://developers.google.com/identity/sign-in/web/deprecation-and-sunset for more information. If you have questions related to authentication/authorization please look at the associated documentation or post questions on Stack Overflow with the google-oauth tag. + +**Summary** +Describe your issue here. + +**Browser(s)/Version(s)** +List browsers and versions affected + +**Expected Behavior** +Tell us what should happen. + +**Actual Behavior** +Tell us what actually happened. + +**Steps to Reproduce** +Please include steps and code samples to aid in issue reproduction(html/javascript). diff --git a/README.md b/README.md index 0c35841..ea482ed 100644 --- a/README.md +++ b/README.md @@ -1,36 +1,32 @@ -# Google APIs Client Library for JavaScript +# Google API Client Library for JavaScript ## Description -Written by Google, this compact and efficient client library provides access to any of Google's RESTful APIs. See below for a list of supported APIs. +The Google API Client Library for JavaScript is designed for JavaScript client-application +developers. It offers simple, flexible access to many Google APIs. -## Beta - -This library is in Beta. We're comfortable enough with the stability and features of the library that we want you to build real production applications on it. We will make an effort to support the public and protected surface of the library and maintain backwards compatibility in the future. While we are still in Beta, we reserve the right to make incompatible changes. If we do remove some functionality (typically because better functionality exists or if the feature proved infeasible), our intention is to deprecate and provide ample time for developers to update their code. +> Note: This repo does not contain the source code for the `gapi` client. ## Features -The JavaScript client library [supports these Google APIs](https://code.google.com/apis/explorer/). +The JavaScript client library [supports these Google APIs](https://developers.google.com/apis-explorer/#p/). + +If you use TypeScript, you can install [`@types/gapi`](https://www.npmjs.com/package/@types/gapi) for autocompletion. -The JavaScript client supports the following browser environments: +# Documentation - - Chrome 8+ - - Firefox 3.5+ - - MSIE 8+ - - Safari 4+ +- [Getting Started](docs/start.md) +- [Reference](docs/reference.md) -The library supports the following authentication and authorization methods - - [OAuth2](https://developers.google.com/api-client-library/javascript/features/authentication) +## Guides -## 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) +- [Auth](docs/auth.md) +- [Batch](docs/batch.md) +- [Discovery Documents](docs/discovery.md) +- [FAQ](docs/faq.md) +- [Promises](docs/promises.md) +- [Samples](docs/samples.md) ## 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) diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..0d5d2b9 --- /dev/null +++ b/docs/README.md @@ -0,0 +1,16 @@ +# 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) +- [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..5e687bc --- /dev/null +++ b/docs/auth.md @@ -0,0 +1,3 @@ +# Authentication + +gapi.auth2 has been deprecated and replaced with Google Identity Services. Please see https://developers.google.com/identity/sign-in/web/deprecation-and-sunset for more information. If you have questions related to authentication/authorization please look at the associated documentation or post questions on Stack Overflow with the google-oauth tag. diff --git a/docs/batch.md b/docs/batch.md new file mode 100644 index 0000000..a612633 --- /dev/null +++ b/docs/batch.md @@ -0,0 +1,78 @@ +# 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](reference.md#batch-api-requests) + +## Creating a batch + +The JavaScript client library defines an object called `Batch`. You can start by instantiating this object: + +```js +const batch = gapi.client.newBatch(); +``` + +## Adding requests to the batch + +Use the `Batch` object's [`add`](reference.md#----gapiclientbatchaddrequestopt_params--) method to add individual HTTP requests. Only requests created via [discovery](discovery.md) should be added to a batch. 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 +const getMe = gapi.client.people.people.get({ + 'resourceName': 'people/me' +}); + +const getYou = gapi.client.people.people.get({ + 'resourceName': 'people/you' +}); + +// Adding just the request +batch.add(getMe); +// Adding the request with an ID +batch.add(getYou, {'id': 'getYou'}); +``` + +## Executing a batch + +Batch requests are executed just like individual requests, using [`gapi.client.Batch.then`](reference.md#----gapiclientbatchthenonfulfilled-onrejected-context--). + +### 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](promises.md) section. 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..9901843 --- /dev/null +++ b/docs/faq.md @@ -0,0 +1,9 @@ +# 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). + +### Is it possible to use the JavaScript client library in a Chrome Extension? + +Chrome Extensions using Manifest v3 do not allow [remotely hosted code](https://developer.chrome.com/docs/extensions/mv3/intro/mv3-overview/#remotely-hosted-code), so the Javascript client library cannot be used in this case. diff --git a/docs/promises.md b/docs/promises.md new file mode 100644 index 0000000..9bae8b5 --- /dev/null +++ b/docs/promises.md @@ -0,0 +1,249 @@ +# 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 + +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); + }); +``` diff --git a/docs/reference.md b/docs/reference.md new file mode 100644 index 0000000..23e728c --- /dev/null +++ b/docs/reference.md @@ -0,0 +1,903 @@ +# 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:iframes". +
+ 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). +

+

+ 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. +

+

+ 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. +
+
diff --git a/docs/samples.md b/docs/samples.md new file mode 100644 index 0000000..e262384 --- /dev/null +++ b/docs/samples.md @@ -0,0 +1,43 @@ +# Samples + +This page provides three detailed examples which demonstrate the library's functionality. Additional samples(including authenticated/authorized requests) can be found in API specific documentation such as the [Google Drive API Quick Start](https://developers.google.com/drive/api/quickstart/js). + +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 + + + + + + +
+ + +``` diff --git a/docs/start.md b/docs/start.md new file mode 100644 index 0000000..0973f55 --- /dev/null +++ b/docs/start.md @@ -0,0 +1,142 @@ +# 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)](discovery.md). +3. The application sends a request and processes the response. + +The following sections show 2 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://github.com/google/google-api-javascript-client/blob/master/docs/samples.md#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 + + +``` + +[](#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, `