JavaScript クイックスタート

クイックスタートでは、Google Workspace API を呼び出すアプリを設定して実行する方法について説明します。

Google Workspace クイックスタートでは、API クライアント ライブラリを使用して認証と認可フローの詳細を処理します。独自のアプリではクライアント ライブラリを使用することをおすすめします。このクイックスタートでは、テスト環境に適した簡略化された認証方法を使用します。本番環境では、アプリに適したアクセス認証情報を選択する前に、認証と認可について確認することをおすすめします。

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

目標

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

前提条件

  • Google アカウント

環境を設定する

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

API を有効にする

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

新しい Google Cloud プロジェクトを使用してこのクイックスタートを完了するには、OAuth 同意画面を構成して、自分自身をテストユーザーとして追加します。Cloud プロジェクトでこの手順をすでに完了している場合は、次のセクションに進みます。

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

    OAuth 同意画面に移動

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

  5. アプリ登録の概要を確認します。変更するには、[編集] をクリックします。アプリ登録に問題がない場合は、[Back to Dashboard] をクリックします。

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

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

    [認証情報] に移動

  2. [認証情報を作成] > [OAuth クライアント ID] をクリックします。
  3. [アプリケーションの種類] > [ウェブ アプリケーション] をクリックします。
  4. [名前] フィールドに、認証情報の名前を入力します。この名前は Google Cloud コンソールにのみ表示されます。
  5. アプリに関連する承認済み URI を追加します。
    • クライアントサイド アプリ(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 コンソールで、メニュー > [API とサービス] > [認証情報] に移動します。

    [認証情報] に移動

  2. [認証情報を作成] > [API キー] をクリックします。
  3. 新しい API キーが表示されます。
    • [コピー] をクリックして、アプリのコードで使用する API キーをコピーします。API キーは、プロジェクトの認証情報の「API キー」セクションでも確認できます。
    • [キーを制限] をクリックして詳細設定を更新し、API キーの使用を制限します。詳しくは、API キーの制限の適用をご覧ください。

サンプルのセットアップ

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

    drive/activity-v2/index.html
    <!DOCTYPE html>
    <html>
      <head>
        <title>Drive Activity API Quickstart</title>
        <meta charset="utf-8" />
      </head>
      <body>
        <p>Drive Activity 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/driveactivity/v2/rest';
    
          // Authorization scopes required by the API; multiple scopes can be
          // included, separated by spaces.
          const SCOPES = 'https://www.googleapis.com/auth/drive.activity.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 listActivities();
            };
    
            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 recent activity.
           */
          async function listActivities() {
            let response;
            try {
              response = await gapi.client.driveactivity.activity.query({
                'pageSize': 10,
              });
            } catch (err) {
              document.getElementById('content').innerText = err.message;
              return;
            }
    
            const activities = response.result.activities;
            if (!activities || activities.length == 0) {
              document.getElementById('content').innerText = 'No activities found.';
              return;
            }
            // Flatten to string to display
            const output = activities.reduce(
                (str, activity) => {
                  const time = getTimeInfo(activity);
                  const action = getActionInfo(activity['primaryActionDetail']);
                  const actors = activity.actors.map(getActorInfo);
                  const targets = activity.targets.map(getTargetInfo);
                  return `${str}${time}: ${truncated(actors)}, ${action}, ${truncated(targets)}\n`;
                },
                'Activities:\n');
            document.getElementById('content').innerText = output;
          }
    
          // Utility methods for formatting activity records
    
          /**
           * Returns a string representation of the first N elements in a list.
           * @param {string[]} array - Values to join
           * @param {number} limit - # of elements to show
           * @return {string} formatted string
           */
          function truncated(array, limit = 2) {
            const contents = array.slice(0, limit).join(', ');
            const more = array.length > limit ? ', ...' : '';
            return `[${contents}${more}]`;
          }
    
          /**
           * Returns the first found property name in an object.
           * @param {object} object - Object to search
           * @return {string} key name or 'unknown'
           */
          function getOneOf(object) {
            const props = Object.getOwnPropertyNames(object);
            if (props.length === 0) {
              return 'unknown';
            }
            return props[0];
          }
    
          /**
           * Returns a time associated with an activity.
           * @param {object} activity - Activity record
           * @return {string} Formatted timestamp
           */
          function getTimeInfo(activity) {
            if ('timestamp' in activity) {
              return activity.timestamp;
            }
            if ('timeRange' in activity) {
              return activity.timeRange.endTime;
            }
            return 'unknown';
          }
    
          /**
           * Returns the type of action.
           * @param {object} actionDetail
           * @return {string} Action type as string
           */
          function getActionInfo(actionDetail) {
            return getOneOf(actionDetail);
          }
    
          /**
           * Returns user information, or the type of user if not a known user.
           * @param {object} user - User record
           * @return {string} user type as string
           */
          function getUserInfo(user) {
            if ('knownUser' in user) {
              const knownUser = user['knownUser'];
              const isMe = knownUser['isCurrentUser'] || false;
              return isMe ? 'people/me' : knownUser['personName'];
            }
            return getOneOf(user);
          }
    
          /**
           * Returns actor information, or the type of actor if not a user.
           * @param {object} actor - Actor record
           * @return {string} actor type as string
           */
          function getActorInfo(actor) {
            if ('user' in actor) {
              return getUserInfo(actor['user']);
            }
            return getOneOf(actor);
          }
    
          /**
           * Returns the type of a target and an associated title.
           * @param {object} target - Activity target record
           * @return {string} target type as string
           */
          function getTargetInfo(target) {
            if ('driveItem' in target) {
              const title = target.driveItem.title || 'unknown';
              return `driveItem:"${title}"`;
            }
            if ('drive' in target) {
              const title = target.drive.title || 'unknown';
              return `drive:"${title}"`;
            }
            if ('fileComment' in target) {
              const parent = target.fileComment.parent || {};
              const title = parent.title || 'unknown';
              return `fileComment:"${title}"`;
            }
            return `${getOneOf(target)}:unknown`;
          }
        </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. アクセスを承認するように求めるプロンプトが表示されます。
    1. Google アカウントにまだログインしていない場合は、ログインを求められたらログインします。複数のアカウントにログインしている場合は、認証に使用するアカウントを 1 つ選択してください。
    2. [Accept] をクリックします。

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

次のステップ