Developing with the JavaScript Client Library

Introduction

The JavaScript client library makes it easier for you to write JavaScript that works with Google services (Calendar, Analytics, etc.) through their APIs. This page shows you how to use the JavaScript client library by example.

Supported environments

The JavaScript client library supports webpages running in the same browsers supported by Google Apps except that mobile browsers are currently not fully supported. In supported browsers it is supported only in HTML documents with a <body> element served using the https (preferred) and http protocols. However, <iframe sandbox> elements and other restricted execution contexts are not supported.

How to access a Google service using the JavaScript client library

To interact with a Google service using the JavaScript client library, your code must do the following:

  • Load the JavaScript client library.
  • Set the access credentials.
  • Load the API for the service you want to work with.
  • Initialize an object that encapsulates the request you want to make.
  • Execute the request object.

The following sections go through each of these tasks.

Loading the client library and the API

To load the JavaScript client library, your code can use a script tag like the following:

<script src="https://apis.google.com/js/api.js"></script>
<script>
  function onLoadFn() {
    // make gapi.client calls
  }
  gapi.load("client", onLoadFn);
</script>

Setting credentials

To get access to Google services using the service APIs, your application must get credentials recognized by Google. Google defines two API access levels:

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 OAuth 2.0 credential

To get Google credentials, follow the instructions on the Getting Started page.

For example, your code can set the API key using the gapi.client.setApiKey method, as follows:

gapi.client.setApiKey(YOUR API KEY);

For details and other code samples that show you how to present credentials to the Google Auth server using the JavaScript client library, see the the Authentication page.

Building and executing the request

The JavaScript client library supports three alternatives for assembling an API request and executing it:

  • Load the API interface first, then initialize the service object to include the parameters of the request, then call this object's then method, in separate commands.
  • Assemble a REST request that specifies the API and the request parameters, then pass it to the client library's request method.
  • Manually assemble and execute the request using CORS.

Option 1: Load the API discovery document, then assemble the request

Once the JavaScript client library is loaded, your code can load a specific API via its API discovery document with a command like the following:

gapi.client.load(API_NAME, API_VERSION, CALLBACK);

Where

  • API_NAME is the name of the API,
  • API_VERSION is the version of the API,
  • CALLBACK is an optional callback function to be executed once the API has been loaded. If a callback is not provided, a Promise-like object is returned.

For example, this code loads version 3 of the Google Drive API:

gapi.client.load('drive', 'v3').then(function() { console.log('loaded.'); });

Some APIs have their discovery documents hosted outside the Discovery API. You need to load such APIs directly via their discovery URLs like this:

gapi.client.load(DISCOVERY_URL).then(...);

For example, this code loads version 1 of the Google Cloud Vision API:

gapi.client.load('https://vision.googleapis.com/$discovery/rest?version=v1').then(function() { console.log('loaded.'); });

Note: A call to gapi.client.load results in a network request to the Discovery API. It is only necessary to call this once per API on a given page.

To review a list of supported APIs and versions, go to the APIs Explorer.

The code that assembles the API request follows this pattern:

// Returns a request object which can be executed (as below) or batched
gapi.client.METHOD_NAME(PARAMETERS_OBJECT).
  then(onFulfilled, onRejected);

For example, you can create an empty file using the Google Drive API using the following method:

gapi.client.drive.files.create({
  'resource': {'name': 'Test file'},
  'useContentAsIndexableText': true
}).then(function(resp) {
  console.log(resp.result);
}, function(reason) {
  console.log('Error: ' + reason.result.error.message);
});

To test API methods on the fly, or see an individual API's documentation for detailed method descriptions, try the APIs Explorer.

The keys of the PARAMETERS_OBJECT correspond to the REST or JSON-RPC parameters for the method being called. The special parameter resource is mapped to the request body for methods which require one, as in the above example.

The service API doesn't support media uploads or downloads, so the example above can't provide any content for the new file; if you needed this, you would have to use CORS instead.

The documentation for each Google service API specifies the REST syntax for its methods. (For links to the documentation for one of these APIs, follow the link for that API on the APIs Explorer page.)

Option 2: Use gapi.client.request

A more general way to make requests is to use gapi.client.request. Your code does not have to load the API first, as in the first option, but it must still set the API key. While you need to manually fill in REST parameters with this option, it saves one network request for loading the API.

To execute the same Google Drive file creation as in the first example, using gapi.client.request:

var restRequest = gapi.client.request({
  'path': '/drive/v3/files',
  'params': {'useContentAsIndexableText': true},
  'body': {'name': 'Test file'}
});
restRequest.then(function(resp) {
  console.log(resp.result);
}, function(reason) {
  console.log('Error: ' + reason.result.error.message);
});

For more on making REST requests, see the API docs for each supported API.

gapi.client.request doesn't support media uploads or downloads. To do this, use CORS instead.

Option 3: Use CORS

The Google APIs support CORS. For more information on using CORS to make requests, see the CORS Support page.

This is the appropriate option if you want to do media uploads or downloads, as it allows precise control of the request body and supports multipart requests.