Google api javascript client

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.

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

Читайте также:  Css outline and border radius
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 .

Name Type Description
urlOrObject string | object The Discovery Document URL or parsed Discovery Document JSON object (Example).
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 .

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.

Name Type Description
apiKey string The API key to set.

gapi.client.setToken( tokenObject )

Sets the authentication token to use in requests.

Читайте также:  Поменять div местами css

API requests

gapi.client.request( args )

Creates a HTTP request for making RESTful requests.

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.

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.

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.

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.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Google APIs Client Library for browser JavaScript, aka gapi.

License

google/google-api-javascript-client

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Update deprecation notice url

Git stats

Files

Failed to load latest commit information.

README.md

Google API Client Library for JavaScript

The Google API Client Library for JavaScript is designed for JavaScript client-application developers. It offers simple, flexible access to many Google APIs.

Note: This repo does not contain the source code for the gapi client.

The JavaScript client library supports these Google APIs.

If you use TypeScript, you can install @types/gapi for autocompletion.

Источник

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.

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

 src="https://apis.google.com/js/api.js"> function start()  // 2. Initialize the JavaScript client library. gapi.client.init( 'apiKey': 'YOUR_API_KEY', // Your API key will be automatically added to the Discovery Document URLs. 'discoveryDocs': ['https://people.googleapis.com/$discovery/rest'], // clientId and scope are optional if auth is not required. 'clientId': 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com', 'scope': 'profile', >).then(function()  // 3. Initialize and make the API request. return gapi.client.people.people.get( 'resourceName': 'people/me', 'requestMask.includeField': 'person.names' >); >).then(function(response)  console.log(response.result); >, function(reason)  console.log('Error: ' + reason.result.error.message); >); >; // 1. Load the JavaScript client library. gapi.load('client', start);  

Option 2: Use gapi.client.request

A more general way to make requests is to use gapi.client.request . 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.

 src="https://apis.google.com/js/api.js"> function start()  // 2. Initialize the JavaScript client library. gapi.client.init( 'apiKey': 'YOUR_API_KEY', // clientId and scope are optional if auth is not required. 'clientId': 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com', 'scope': 'profile', >).then(function()  // 3. Initialize and make the API request. return gapi.client.request( 'path': 'https://people.googleapis.com/v1/people/me?requestMask.includeField=person.names', >) >).then(function(response)  console.log(response.result); >, function(reason)  console.log('Error: ' + reason.result.error.message); >); >; // 1. Load the JavaScript client library. gapi.load('client', start);  

Supported environments

The JavaScript client library works with the same browsers supported by Google Apps 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, elements and other restricted execution contexts are not supported.

Use of this JavaScript client library is not supported in Chrome Browser extensions using Manifest v3 due to the No remotely hosted code requirement.

Setup

Get a Google Account

First, sign up for a Google Account if you do not already have one.

Create a Google project

Go to the Google API Console. Click Create project, enter a name, and click Create.

Enable Google APIs

Next, decide which Google APIs your application needs to use and enable them for your project. Use the APIs Explorer to explore Google APIs that the JavaScript client library can work with.

To enable an API for your project, do the following:

  1. Open the API Library in the Google API Console. If prompted, select a project or create a new one. The API Library lists all available APIs, grouped by product family and popularity.
  2. If the API you want to enable isn’t visible in the list, use search to find it.
  3. Select the API you want to enable, then click the Enable button.
  4. If prompted, enable billing.
  5. If prompted, accept the API’s Terms of Service.

Get access keys for your application

Google defines two levels of API access:

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 credentials

To acquire an API key for simple access, do the following:

  1. Open the Credentials page in the “APIs & Services” console.
  2. Click Create credentials > API key and select the appropriate key type.

To keep your API keys secure, follow the best practices for securely using API keys.

To acquire OAuth 2.0 credentials for authorized access, do the following:

  1. Open the Credentials page in the “APIs & Services” console.
  2. Click Create credentials > OAuth client ID and select the appropriate Application type.

Источник

Оцените статью