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.

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.

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)

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.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. See
gapi.auth2.ClientConfig for the different
properties configurable. For example:

{
client_id: 'CLIENT_ID.apps.googleusercontent.com'
}

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, onError)

Calls the onInit function when the GoogleAuth object is fully
initialized. If an error is raised while initializing (this can happen in old unsupported browsers),
the onError function will be called instead.

Arguments

onInit

The function called with the GoogleAuth object when it is fully
initialized.

onError

The function called with an object containing an error property,
if GoogleAuth failed to initialize.

Returns

Promise

A Promise that is fulfilled when the onInit
function has completed, or rejected if an initialization error was raised. It resolves with the
returned value from the onInit function, if any.

Warning: do not call Promise.resolve() and similar with the result of
gapi.auth2.init(). As the GoogleAuth object returned implements the
then() method that resolves with itself, it will create an infinite recursion.

Error codes

idpiframe_initialization_failed

Failed to initialize a required iframe from Google, for instance, due to an unsupported
environment. A details property will give more information on the error raised.

gapi.auth2.ClientConfig

Interface that represents the different configuration parameters for the
gapi.auth2.init method.

Parameters

client_id

string

Required. The app's client ID, found and created in the Google Developers Console.

cookie_policy

string

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

string

The scopes to request, as a space-delimited string. Optional if
fetch_basic_profile is not set to false.

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.
You must request the 'email' scope when using this parameter alongside
fetch_basic_profile: false.

openid_realm

string

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

ux_mode

string

The UX mode to use for the sign-in flow. By default, it will open the consent flow
in a popup. Valid values are popup and redirect.

redirect_uri

string

If using ux_mode='redirect', this parameter allows you to override the
default redirect_uri that will be used at the end of the consent flow. The
default redirect_uri is the current URL stripped of query parameters and hash
fragment.

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 with the GoogleUser instance when the
user successfully authenticates and grants the requested scopes, or rejected with an object
containing an error property if an error happened (see below for error codes).

A Promise that is fulfilled with the GoogleUser instance when the
user successfully authenticates and grants the requested scopes, or rejected with an object
containing an error property if an error happened (see below for error codes).

Error codes

popup_closed_by_user

The user closed the popup before finishing the sign in flow.

access_denied

The user denied the permission to the scopes required.

immediate_failed

No user could be automatically selected without prompting the consent flow. Error raised when
using signIn with prompt: 'none' option. This option should not be
required to use, as gapi.auth2.init will automatically sign in the user if
previously signed in during a previous session.

Forces a specific mode for the consent flow. Optional.
The possible values are:

consent
The authorization server prompts the user for consent before returning
information to the application.

select_account
The authorization server prompts the user to select a Google account. This
allows a user who has multiple accounts to select amongst the multiple accounts
that they may have current sessions for.

none (not recommended)
The authorization server will not display any authentication or user consent
screens; it will return an error if the user is not already authenticated and
has not previously consented to the requested scopes.
As gapi.auth2.init will automatically sign in a user to the
application if previously signed in, calling
signIn({prompt: 'none'}) will usually fail.

scope

string

The scopes to request, as a space-delimited string, on top of the scopes defined in the
gapi.auth2.init params. Optional if fetch_basic_profile is not set
to false.

ux_mode

string

The UX mode to use for the sign-in flow. By default, it will open the consent flow
in a popup. Valid values are popup and redirect.

redirect_uri

string

If using ux_mode='redirect', this parameter allows you to override
the default redirect_uri that will be used at the end of the consent
flow. The default redirect_uri is the current URL stripped of query
parameters and hash fragment.

Error codes

popup_closed_by_user

The user closed the popup before finishing the consent flow.

access_denied

The user denied the permission to the scopes required.

immediate_failed

No user could be automatically selected without prompting the consent flow. Error raised when
using signIn with prompt: 'none' option. This option should not be
required to use, as gapi.auth2.init will automatically sign in the user if
previously signed in during a previous session.

Forces a specific mode for the consent flow. Optional.
The possible values are:

consent
The authorization server prompts the user for consent before returning
information to the application.

select_account
The authorization server prompts the user to select a Google account. This
allows a user who has multiple accounts to select amongst the multiple accounts
that they may have current sessions for.

Note that none is not available for the offline code flow.

scope

string

The scopes to request, as a space-delimited string, on top of the scopes defined in the
gapi.auth2.init params. Optional if fetch_basic_profile is not set
to false.

Users

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.

Do not use the Google IDs returned by
getId() to communicate the currently signed in user to your backend
server. Instead, send ID
tokens, which can be securely validated on the server.

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.

Do not use the user's profile information to
communicate the currently signed in user to your backend server. Instead,
send ID tokens, which can be
securely validated on the server.

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(includeAuthorizationData)

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

Arguments

includeAuthorizationData

Optional: A boolean that specifies whether to always return an access token and
scopes. By default, the access token and requested scopes are not returned when
fetch_basic_profile is true (the default value) and no additional scopes are
requested.

Advanced

Warning: this section covers features that are not recommended for most use cases. Make
sure that the methods described in the Guides don't work for your use case before using such
features.

gapi.auth2.authorize(params, callback)

Performs a one time OAuth 2.0 authorization. Depending on the parameters used, this will open a
popup to the Google sign-in flow or try to load the requested response silently, without user
interaction.

Some use cases where this method is useful include:

Your application only needs to requests a Google API endpoint once, for instance to load
the user's favorite YouTube videos the first time they sign in.

Your application has its own session management infrastructure, and it only requires the
ID Token once to identify the user in your backend.

Several Client IDs are used within the same page.

Warning: do not use this method alongside the recommended
gapi.auth2.init and signIn flow.
These are two distinct behaviors (Authorization for gapi.auth2.authorize vs
Authentication for gapi.auth2.init/signIn) and will have unexpected issues if used
within the same application.

Arguments

params

An object containing key-value pairs of configuration data. See
gapi.auth2.AuthorizeConfig for the
different properties configurable. For example:

Error codes

Failed to initialize a required iframe from Google, for instance, due to an unsupported
environment. A details property will give more information on the error raised.

popup_closed_by_user

The user closed the popup before finishing the sign in flow.

access_denied

The user denied the permission to the scopes required.

immediate_failed

No user could be automatically selected without prompting the consent flow. Error raised when
using signIn with prompt: 'none' option.

gapi.auth2.AuthorizeConfig

Interface that represents the different configuration parameters for the
gapi.auth2.authorize method.

Properties

client_id

string

Required. The app's client ID, found and created in the Google Developers Console.

scope

string

Required. The scopes to request, as a space-delimited string.

response_type

string

A list of space-delimited response type. Defaults to 'permission'. The possible
values are:

id_token, to retrieve an ID Token

permission (or token), to retrieve an Access Token

code, to retrieve an Authorization Code

prompt

string

Forces a specific mode for the consent flow. The possible values are:

consent
The authorization server prompts the user for consent before returning
information to the application.

select_account
The authorization server prompts the user to select a Google account. This
allows a user who has multiple accounts to select amongst the multiple accounts
that they may have current sessions for.

none
The authorization server will not display any authentication or user consent
screens; it will return an error if the user is not already authenticated and
has not previously consented to the requested scopes.
If code is requested as response type, the code returned will only be
exchangeable for an access_token, not a refresh_token.
Note : under the hood, the library caches and automatically refreshes the last
Access Token obtained. When using prompt: 'none', most of the time, no HTTP
request to the backend will be necessary to obtain a valid token.

cookie_policy

string

The domains for which to create sign-in cookies. Either a URI,
single_host_origin, or none. Defaults to
single_host_origin if unspecified.

hosted_domain

string

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.

login_hint

string

The email, or User ID, of a user to pre-select in the sign-in flow. This is susceptible to
modification by the user, unless prompt: "none" is used.