Google APIs Client Library for JavaScript (Beta)

Developing with the JavaScript client library

Contents

  1. Introduction
    1. Supported environments
    2. How to access a Google service using the JavaScript client library
  2. Loading the client library and the API
  3. Setting credentials
  4. Building and executing the request
    1. Option 1: Load the service API, then assemble the request
      1. Example: Google Cloud Storage
      2. Assembling a JSON-RPC request
    2. Option 2: Use gapi.client.request to make REST request
    3. Option 3: Use CORS
  5. Processing the results

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.

This video from Google I/O 2012 is a good overview of what Google APIs are and how to consume them using the JavaScript client library:

Supported environments

The JavaScript client library supports the following browser environments:

  • Chrome 8+
  • Firefox 3.5+
  • MSIE 8+
  • Safari 4+

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/client.js?onload=OnLoadCallback"></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.

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 execute 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
  • Assemble and execute the request using CORS

Option 1: Load the service API, then assemble the request

Once the JavaScript client library is loaded, your code can load a specific API 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.

Example: this code loads version 1 of the Google+ API:

gapi.client.load('plus', 'v1', function() { console.log('loaded.'); });

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
  var ApiRequest = gapi.client.METHOD_NAME(PARAMETERS_OBJECT);
ApiRequest.execute(callback);
Example: you can send a search request to the Google+ API using the following method:

var request = gapi.client.plus.activities.search({'query': 'Google+', 'orderBy': 'best'});
request.execute(function(resp) { console.log(resp); });

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

When you use this pattern to assemble and then execute a request, you have two alternatives for the syntax of the PARAMETERS_OBJECT: REST or JSON-RPC.

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

The following section documents the JSON-RPC equivalent of a request's REST syntax.

Example: Google Cloud Storage

This example demonstrates adding the elements of a REST request to an RPC request. The documentation for the storage.objects.insert method describes the REST format:

  • This method takes one required path parameter (Name: bucket, type: string — the bucket to insert to) and two optional URL parameters. In a JSON-RPC request, all three are passed to the JSON-RPC call.
  • The method also takes a required HTTP body. The documentation does not specify a name for this parameter, so this example names it "resource".

Sample REST request:

  var bucketId = 'ID of bucket where object will be inserted';
  var request = gapi.client.request({
    'path': '/storage/v1beta1/b/' + bucketId + '/o',
    // As specified by docs, this should not be given for JSON-RPC requests
    'method': 'POST',
    // Optional parameter specified by docs
    'params': {'name': 'objectName'},
    // body format also described in docs
    'body': {
      'media': {
        'contentType': 'application/json',
        'data': 'object content'
      }
    }
  });

The same request in JSON-RPC format:

  var request = gapi.client.storage.objects.insert({
    // Parameters from the REST request, both path and URL params
    'bucket': bucketId,
    'name': 'objectName',
    // body included as 'resource' param
    'resource': {
      'media': {
        'contentType': 'application/json',
        'data': 'object content'
      }
    }
  });

Assembling a JSON-RPC request

Here are a few tips for forming the JSON-RPC equivalent of a REST request:

  • You can include anything listed in the API documentation as a parameter in the key-value params object which your code passes to a JSON-RPC request. This is true for path params and URL params (see the example below).
  • If a REST API accepts an HTTP body, your code can add that body the RPC request as a resource parameter, unless the API documentation specifies otherwise.
  • The HTTP method (GET, POST, etc.) should not be specified in a JSON-RPC request.

Option 2: Use gapi.client.request to make REST requests

A more general way to make requests is to use gapi.client.request. Your code does not have to load the client library first, as in the first option, but it must still set the API key.

To execute the same Google+ search as in the first example, using gapi.client.request:

var restRequest = gapi.client.request({
  'path': '/plus/v1/activities',
  'params': {'query': 'Google+', 'orderBy': 'best'}
});
restRequest.execute(function(resp) { console.log(resp); });

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

Option 3: Use CORS

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

Processing the results

Your application must define a method to handle the API's response to a request. Your code must specify this method as the callback to the execute function.

The API returns two objects to the callback function. In the Reference documentation, these are referred to as jsonResp and rawResp.

The data returned by most Google APIs comes in the JSON format, but there are notable exceptions (media objects, for example). The JavaScript client library is engineered to handle two types of returned objects, JSON and non-JSON. The content of the two objects returned to the callback function differs in each case, as follows:

If ... Content of jsonResp Content of rawResp
The returned object is JSON the JSON object the HTTP response (same object, but not parsed as JSON)
The returned object is not JSON The value false the HTTP response (an unparsed string)

Authentication required

You need to be signed in with Google+ to do that.

Signing you in...

Google Developers needs your permission to do that.