JavaScript クイックスタート

クイックスタートでは、 Google Workspace API

Google Workspace クイックスタートでは、API クライアント ライブラリを使用して 認証と認可のフローの詳細を確認できます。おすすめの方法 独自のアプリ用のクライアント ライブラリを使用します。このクイックスタートでは、 テストに適したシンプルな認証アプローチ できます。本番環境では、Terraform の IAM 構成の 認証と認可 次の日付より前 アクセス認証情報の選択 選択することもできます

People API にリクエストを送信する JavaScript ウェブ アプリケーションを作成します。

目標

  • 環境を設定する。
  • サンプルを設定します。
  • サンプルを実行します。

前提条件

  • API アクセスが有効になっている Google Workspace ドメイン。
  • そのドメイン内の管理者権限を持つ Google アカウント。

環境の設定

このクイックスタートを完了するには、環境を設定します。

API を有効にする

Google API を使用する前に、Google Cloud プロジェクトで有効にする必要があります。 1 つの Google Cloud プロジェクトで 1 つ以上の API を有効にできます。
  • Google Cloud コンソールで、People API を有効にします。

    API の有効化

このクイックスタートを完了するために新しい Google Cloud プロジェクトを使用する場合は、 OAuth 同意画面を開き、自分自身をテストユーザーとして追加します。すでに 完了している場合は、次のセクションにスキップしてください。

  1. Google Cloud コンソールで、メニュー に移動します。 > API とサービス > OAuth 同意画面

    OAuth 同意画面に移動

  2. [ユーザーの種類] で [内部] を選択し、[作成] をクリックします。
  3. アプリ登録フォームに入力し、[保存して次へ] をクリックします。
  4. 現時点では、スコープの追加をスキップして [保存して次へ] をクリックします。 今後、Google Play 以外で使用するアプリを作成した場合、 [ユーザーの種類] を [外部] に変更してから、 アプリに必要な認証スコープを追加します。

  5. アプリ登録の概要を確認します。変更するには、[編集] をクリックします。アプリが 問題がなければ、[ダッシュボードに戻る] をクリックします。

ウェブ アプリケーションの認証情報を承認する

エンドユーザーを認証してアプリでユーザーデータにアクセスするには、次のことを行う必要があります。 OAuth 2.0 クライアント ID を作成します。クライアント ID は Google の OAuth サーバーに送信します。アプリが複数のプラットフォームで動作する場合 プラットフォームごとに個別のクライアント ID を作成する必要があります。
  1. Google Cloud コンソールで、メニュー > [API と[サービス] > [認証情報] に移動します。

    [認証情報] に移動

  2. [認証情報を作成] > [OAuth クライアント ID] をクリックします。
  3. [アプリケーションの種類] > [ウェブ アプリケーション] をクリックします。
  4. [名前] フィールドに、認証情報の名前を入力します。この名前は Google Cloud コンソールにのみ表示されます。
  5. アプリに関連する承認済み URI を追加します。 <ph type="x-smartling-placeholder">
      </ph>
    • クライアントサイド アプリ(JavaScript) - [承認済みの JavaScript 生成元] で [URI を追加] をクリックします。次に、ブラウザ リクエストに使用する URI を入力します。アプリケーションが OAuth 2.0 サーバーに API リクエストを送信できるドメインを識別します。
    • サーバーサイド アプリ(Java、Python など) - [承認済みのリダイレクト URI] で [URI を追加] をクリックします。次に、OAuth 2.0 サーバーがレスポンスを送信できるエンドポイント URI を入力します。
  6. [作成] をクリックします。OAuth クライアントの作成画面が表示され、新しいクライアント ID とクライアント シークレットが表示されます。

    クライアント ID をメモします。クライアント シークレットはウェブ アプリケーションには使用されません。

  7. [OK] をクリックします。新しく作成された認証情報が [OAuth 2.0 クライアント ID] に表示されます。

このクイックスタートの後半で必要になるため、これらの認証情報をメモしておきます。

API キーを作成する

  1. Google Cloud コンソールで、メニュー に移動します。 &gt; API とサービス &gt; [認証情報] をタップします。

    [認証情報] に移動

  2. [認証情報を作成] &gt; をクリックします。 API キー
  3. 新しい API キーが表示されます。
    • コピーアイコン をクリックします。 して、アプリのコードで使用する API キーをコピーします。API キーは [API キー] セクションでセクションに追加します。
    • 詳細設定を更新して使用を制限するには、[キーを制限] をクリックします 指定します。詳しくは、API キーの制限を適用するをご覧ください。

サンプルのセットアップ

  1. 作業ディレクトリに、index.html という名前のファイルを作成します。
  2. index.html ファイルに次のサンプルコードを貼り付けます。

    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>

    次のように置き換えます。

サンプルの実行

  1. 作業ディレクトリに http-server パッケージをインストールします。

    npm install http-server
    
  2. 作業ディレクトリでウェブサーバーを起動します。

    npx http-server -p 8000
    
  1. ブラウザで http://localhost:8000 にアクセスします。
  2. アクセスの承認を求めるメッセージが表示されます。 <ph type="x-smartling-placeholder">
      </ph>
    1. Google アカウントにまだログインしていない場合は、ログインを求められたらログインします。条件 複数のアカウントにログインしている場合は、承認に使用するアカウントを 1 つ選択してください。
    2. [Accept] をクリックします。

JavaScript アプリケーションが、People API を実行して呼び出します。

次のステップ