JavaScript quickstart

Stay organized with collections Save and categorize content based on your preferences.

Quickstarts explain how to set up and run an app that calls a Google Workspace API.

Google Workspace quickstarts use the API client libraries to handle some details of the authentication and authorization flow. We recommend that you use the client libraries for your own apps. Before you can run the sample app, each quickstart requires that you turn on authentication and authorization. If you're unfamiliar with authentication and authorization for Google Workspace APIs, read the Authentication and authorization overview.

Create a JavaScript command-line application that makes requests to the People API.

Objectives

  • Set up your environment.
  • Set up the sample.
  • Run the sample.

Prerequisites

  • A Google Workspace domain with API access enabled.
  • A Google Account in that domain with administrator privileges.

Set up your environment

To complete this quickstart, set up your environment.

Enable the API

Before using Google APIs, you need to turn them on in a Google Cloud project. You can turn on one or more APIs in a single Google Cloud project.

Authorize credentials for a web application

To authenticate as an end user and access user data in your app, you need to create one or more OAuth 2.0 Client IDs. A client ID is used to identify a single app to Google's OAuth servers. If your app runs on multiple platforms, you must create a separate client ID for each platform.
  • In the Google Cloud console, go to Menu > APIs & Services > Credentials.

    Go to Credentials

  • Click Create Credentials > OAuth client ID.
  • Click Application type > Web application.
  • In the "Name" field, type a name for the credential. This name is only shown in the Google Cloud console.
  • Add authorized URIs related to your app:
    • Client-side apps (JavaScript) – Under Authorized JavaScript origins, click Add URI. Then, enter a URI to use for browser requests. This identifies the domains from which your application can send API requests to the OAuth 2.0 server.
    • Server-side apps (Java, Python, .NET, and more) – Under "Authorized redirect URIs," click Add URI. Then, enter an endpoint URI to which the OAuth 2.0 server can send responses.
  • Click Create. The OAuth client created screen appears, showing your new Client ID and Client secret.
  • Note the Client ID. Client secrets aren't used for Web applications.
  • Click OK. The newly created credential appears under "OAuth 2.0 Client IDs."
  • Optional: If you're creating credentials as a prerequisite for a JavaScript quickstart, you must also generate an API key.
  • Make a note of these credentials because you need them later in this quickstart.

    Set up the sample

    1. In your working directory, create a file named index.html.
    2. In the index.html file, paste the following sample code:

      people/quickstart/index.html
      <!DOCTYPE html>
      <html>
        <head>
          <title>People API Quickstart</title>
          <meta charset="utf-8" />
        </head>
        <body>
          <p>People API Quickstart</p>
      
          <!--Add buttons to initiate auth sequence and sign out-->
          <button id="authorize_button" onclick="handleAuthClick()">Authorize</button>
          <button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>
      
          <pre id="content" style="white-space: pre-wrap;"></pre>
      
          <script type="text/javascript">
            /* exported gapiLoaded */
            /* exported gisLoaded */
            /* exported handleAuthClick */
            /* exported handleSignoutClick */
      
            // TODO(developer): Set to client ID and API key from the Developer Console
            const CLIENT_ID = '<YOUR_CLIENT_ID>';
            const API_KEY = '<YOUR_API_KEY>';
      
      
            // Discovery doc URL for APIs used by the quickstart
            const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/people/v1/rest';
      
            // Authorization scopes required by the API; multiple scopes can be
            // included, separated by spaces.
            const SCOPES = 'https://www.googleapis.com/auth/contacts.readonly';
      
            let tokenClient;
            let gapiInited = false;
            let gisInited = false;
      
            document.getElementById('authorize_button').style.visibility = 'hidden';
            document.getElementById('signout_button').style.visibility = 'hidden';
      
            /**
             * Callback after api.js is loaded.
             */
            function gapiLoaded() {
              gapi.load('client', initializeGapiClient);
            }
      
            /**
             * Callback after the API client is loaded. Loads the
             * discovery doc to initialize the API.
             */
            async function initializeGapiClient() {
              await gapi.client.init({
                apiKey: API_KEY,
                discoveryDocs: [DISCOVERY_DOC],
              });
              gapiInited = true;
              maybeEnableButtons();
            }
      
            /**
             * Callback after Google Identity Services are loaded.
             */
            function gisLoaded() {
              tokenClient = google.accounts.oauth2.initTokenClient({
                client_id: CLIENT_ID,
                scope: SCOPES,
                callback: '', // defined later
              });
              gisInited = true;
              maybeEnableButtons();
            }
      
            /**
             * Enables user interaction after all libraries are loaded.
             */
            function maybeEnableButtons() {
              if (gapiInited && gisInited) {
                document.getElementById('authorize_button').style.visibility = 'visible';
              }
            }
      
            /**
             *  Sign in the user upon button click.
             */
            function handleAuthClick() {
              tokenClient.callback = async (resp) => {
                if (resp.error !== undefined) {
                  throw (resp);
                }
                document.getElementById('signout_button').style.visibility = 'visible';
                document.getElementById('authorize_button').innerText = 'Refresh';
                await listConnectionNames();
              };
      
              if (gapi.client.getToken() === null) {
                // Prompt the user to select a Google Account and ask for consent to share their data
                // when establishing a new session.
                tokenClient.requestAccessToken({prompt: 'consent'});
              } else {
                // Skip display of account chooser and consent dialog for an existing session.
                tokenClient.requestAccessToken({prompt: ''});
              }
            }
      
            /**
             *  Sign out the user upon button click.
             */
            function handleSignoutClick() {
              const token = gapi.client.getToken();
              if (token !== null) {
                google.accounts.oauth2.revoke(token.access_token);
                gapi.client.setToken('');
                document.getElementById('content').innerText = '';
                document.getElementById('authorize_button').innerText = 'Authorize';
                document.getElementById('signout_button').style.visibility = 'hidden';
              }
            }
      
            /**
             * Print the display name if available for 10 connections.
             */
            async function listConnectionNames() {
              let response;
              try {
                // Fetch first 10 files
                response = await gapi.client.people.people.connections.list({
                  'resourceName': 'people/me',
                  'pageSize': 10,
                  'personFields': 'names,emailAddresses',
                });
              } catch (err) {
                document.getElementById('content').innerText = err.message;
                return;
              }
              const connections = response.result.connections;
              if (!connections || connections.length == 0) {
                document.getElementById('content').innerText = 'No connections found.';
                return;
              }
              // Flatten to string to display
              const output = connections.reduce(
                  (str, person) => {
                    if (!person.names || person.names.length === 0) {
                      return `${str}Missing display name\n`;
                    }
                    return `${str}${person.names[0].displayName}\n`;
                  },
                  'Connections:\n');
              document.getElementById('content').innerText = output;
            }
          </script>
          <script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
          <script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
        </body>
      </html>

      Replace the following:

    Run the sample

    1. In your working directory, start a web server:

      Python 2.x

      python -m SimpleHTTPServer 8000
      

      Python 3.x

      python3 -m http.server 8000
      
    2. In your browser, navigate to http://localhost:8000.

    3. The first time you run the sample, it prompts you to authorize access:

      1. If you're not already signed in to your Google Account, you're prompted to sign in. If you're signed in to multiple accounts, select one account to use for authorization.
      2. Click Accept.
      3. Copy the code from the browser, paste it into the command-line prompt, and press Enter.

      Authorization information is stored in the file system, so the next time you run the sample code, you aren't prompted for authorization.

    You have successfully created your first JavaScript application that makes requests to the People API.

    Next steps