Methods and Classes

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

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.

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.

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.

Auth setup

gapi.auth2.init(params)

Initializes the GoogleAuth object. You must call this method before calling gapi.auth2.GoogleAuth's methods.

When you initialize the GoogleAuth object, you configure the object with your OAuth 2.0 client ID and any additional options you want to specify. Then, if the user has already signed in, the GoogleAuth object restores the user's sign-in state from the previous session.

Arguments
params An object containing key-value pairs of client configuration data. For example:
{
client_id: 'CLIENT_ID.apps.googleusercontent.com'
// Additional optional params
}
You can specify the following parameters:
Parameters
client_id The app's client ID, found and created in the Google Developers Console.
cookie_policy The domains for which to create sign-in cookies. Either a URI, single_host_origin, or none. Defaults to single_host_origin if unspecified.
scope The scopes to request, as a space-delimited string. Optional if fetch_basic_profile is not set to false.
fetch_basic_profile Fetch users' basic profile information when they sign in. Adds 'profile' and 'email' to the requested scopes. True if unspecified.
hosted_domain The G Suite domain to which users must belong to sign in. This is susceptible to modification by clients, so be sure to verify the hosted domain property of the returned user. Use GoogleUser.getHostedDomain() on the client, and the hd claim in the ID Token on the server to verify the domain is what you expected. Optional.
openid_realm Used only for OpenID 2.0 client migration. Set to the value of the realm that you are currently using for OpenID 2.0, as described in OpenID 2.0 (Migration).
Returns
gapi.auth2.GoogleAuth The gapi.auth2.GoogleAuth object. Use the then() method to get a Promise that is resolved when the gapi.auth2.GoogleAuth object finishes initializing.

GoogleAuth.then(onInit)

Calls the onInit function when the GoogleAuth object is fully initialized.

Arguments
onInit() The function to call when the GoogleAuth object is fully initialized.
Returns
Promise A Promise that is fulfilled when the onInit function has completed.

Authentication

GoogleAuth is a singleton class that provides methods to allow the user to sign in with a Google account, get the user's current sign-in status, get specific data from the user's Google profile, request additional scopes, and sign out from the current account.

gapi.auth2.getAuthInstance()

Returns the GoogleAuth object. You must initialize the GoogleAuth object with gapi.auth2.init() before calling this method.

Returns
gapi.auth2.GoogleAuth The gapi.auth2.GoogleAuth object. Use this object to call gapi.auth2.GoogleAuth's methods.

GoogleAuth.isSignedIn.get()

Returns whether the current user is currently signed in.

Returns
Boolean true if the user is signed in, or false if the user is signed out or the GoogleAuth object isn't initialized.

GoogleAuth.isSignedIn.listen(listener)

Listen for changes in the current user's sign-in state.

Arguments
listener A function that takes a boolean value. listen() passes true to this function when the user signs in, and false when the user signs out.

GoogleAuth.signIn()

Signs in the user with the options specified to gapi.auth2.init().

Returns
Promise A Promise that is fulfilled when the user successfully authenticates and grants the requested scopes.

GoogleAuth.signIn(options)

Signs in the user using the specified options.

Arguments
options Either:
  • An object containing key-value pairs of sign-in parameters. For example:
    {
      'scope': 'profile email'
    }
    You can specify the following parameters:
    Parameters
    app_package_name The package name of the Android app to install over the air. See Android app installs from your web site. Optional.
    fetch_basic_profile Fetch users' basic profile information when they sign in. Adds 'profile' and 'email' to the requested scopes. Optional. True if unspecified.
    prompt Specifies whether to prompt the user for re-authentication. See OpenID Connect Request Parameters. Optional.
    scope The scopes to request, as a space-delimited string. Optional if fetch_basic_profile is not set to false.
  • An instance of gapi.auth2.SigninOptionsBuilder. For example:
    options = new gapi.auth2.SigninOptionsBuilder();
    options.setAppPackageName('com.example.app');
    options.setFetchBasicProfile(True);
    options.setPrompt('select_account');
    options.setScope('profile').setScope('email');
Returns
Promise A Promise that is fulfilled when the user successfully authenticates and grants the requested scopes.

GoogleAuth.signOut()

Signs out the current account from the application.

Returns
Promise A Promise that is fulfilled when the user has been signed out.

GoogleAuth.disconnect()

Revokes all of the scopes that the user granted.

GoogleAuth.grantOfflineAccess(options)

Get permission from the user to access the specified scopes offline.

Arguments
options An object containing key-value pairs of parameters. For example:
{
  'scope': 'profile email',
  'redirect_uri': 'http://myownpersonaldomain.com/code'
}
The scopes that you specify here are requested in addition to the scopes specified to gapi.auth2.init(). In the redirect_uri field, you can either specify the URI of your server's authorization code handler or the string postmessage, in which case the authorization code is encapsulated in the Promise that is returned.
Returns
Promise A Promise that is fulfilled when the user grants the requested scopes. If you specified postmessage, the Promise passes an object containing the authorization code to the Promise's fulfillment handler. For example:
auth2.grantOfflineAccess({'redirect_uri': 'postmessage'}).then(function(resp) {
  var auth_code = resp.code;
});

GoogleAuth.attachClickHandler(container, options, onsuccess, onfailure)

Attaches the sign-in flow to the specified container's click handler.

Arguments
container The ID of, or a reference to, the div element to which to attach the click handler.
options An object containing key-value pairs of parameters. See GoogleAuth.signIn().
onsuccess The function to call after sign-in completes.
onfailure The function to call if sign-in fails.

Users

A GoogleUser object represents one user account. GoogleUser objects are typically obtained by calling GoogleAuth.currentUser.get().

GoogleAuth.currentUser.get()

Returns a GoogleUser object that represents the current user. Note that in a newly-initialized GoogleAuth instance, the current user has not been set. Use the currentUser.listen() method or the GoogleAuth.then() to get an initialized GoogleAuth instance.

Returns
GoogleUser The current user

GoogleAuth.currentUser.listen(listener)

Listen for changes in currentUser.
Arguments
listener A function that takes a GoogleUser parameter. listen passes this function a GoogleUser instance on every change that modifies currentUser.

GoogleUser.getId()

Get the user's unique ID string.

Returns
String The user's unique ID

GoogleUser.isSignedIn()

Returns true if the user is signed in.

Returns
Boolean True if the user is signed in

GoogleUser.getHostedDomain()

Get the user's G Suite domain if the user signed in with a G Suite account.

Returns
String The user's G Suite domain

GoogleUser.getGrantedScopes()

Get the scopes that the user granted as a space-delimited string.

Returns
String The scopes granted by the user

GoogleUser.getBasicProfile()

Get the user's basic profile information.

Returns
gapi.auth2.BasicProfile You can retrieve the properties of gapi.auth2.BasicProfile with the following methods:
  • BasicProfile.getId()
  • BasicProfile.getName()
  • BasicProfile.getGivenName()
  • BasicProfile.getFamilyName()
  • BasicProfile.getImageUrl()
  • BasicProfile.getEmail()

GoogleUser.getAuthResponse()

Get the response object from the user's auth session.

Returns
gapi.auth2.AuthResponse An AuthResponse object has the following properties:
  • access_token (string)
  • id_token (string)
  • login_hint (string)
  • scope (string)
  • expires_in (string)
  • first_issued_at (string)
  • expires_at (string)

GoogleUser.reloadAuthResponse()

Forces a refresh of the access token, and then returns a Promise for the new AuthResponse.

Returns
Promise A Promise that is fulfilled with the reloaded AuthResponse when reloading the OAuth token is done.

GoogleUser.hasGrantedScopes(scopes)

Returns true if the user granted the specified scopes.

Arguments
scopes A space-delimited string of scopes.
Returns
Boolean True if the scopes were granted

GoogleUser.grant(options)

See GoogleUser.signIn().

GoogleUser.grantOfflineAccess(scopes)

Get permission from the user to access the specified scopes offline. When you use GoogleUser.grantOfflineAccess(), the sign-in flow skips the account chooser step.

See GoogleUser.grantOfflineAccess().

GoogleUser.disconnect()

Revokes all of the scopes that the user granted.

UI elements

gapi.signin2.render(id, options)

Renders a sign-in button in the element with the given ID, using the settings specified by the options object.

Arguments
id The ID of the element in which to render the sign-in button.
options An object containing the settings to use to render the button. For example:
{
'scope': 'email',
'width': 200,
'height': 50,
'longtitle': true,
'theme': 'dark',
'onsuccess': handleSuccess,
'onfailure': handleFailure
}
You can specify the following options:
Parameters
scope The scopes to request when the user signs in (default: profile).
width The width of the button in pixels (default: 120).
height The height of the button in pixels (default: 36).
longtitle Display long labels such as "Sign in with Google" rather than "Sign in" (default: false).
theme The color theme of the button: either light or dark (default: light).
onsuccess The callback function to call when a user successfully signs in. This function must take one argument: an instance of gapi.auth2.GoogleUser (default: none).
onfailure The callback function to call when sign-in fails. This function takes no arguments (default: none).
app_package_name The package name of the Android app to install over the air. See Android app installs from your web site. Optional. (default: none)