JavaScript クイックスタート

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

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

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

目標

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

前提条件

  • Google ドライブが有効になっている Google アカウント。

環境の設定

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

API を有効にする

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

    API の有効化

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

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

    OAuth 同意画面に移動

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

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

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

エンドユーザーを認証してアプリでユーザーデータにアクセスするには、次のことを行う必要があります。 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 キーの制限を適用するをご覧ください。

サンプルのセットアップ

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

    apps-script/quickstart/index.html
    <!DOCTYPE html>
    <html>
      <head>
        <title>Google Apps Script API Quickstart</title>
        <meta charset="utf-8" />
      </head>
      <body>
        <p>Google Apps Script 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://script.googleapis.com/$discovery/rest?version=v1';
    
          // Authorization scopes required by the API; multiple scopes can be
          // included, separated by spaces.
          const SCOPES = 'https://www.googleapis.com/auth/script.projects';
    
          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 createScript();
            };
    
            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';
            }
          }
    
          /**
           * Creates a new 'Hello world' script.
           */
          async function createScript() {
            let response;
            try {
              const createRequest = {
                resource: {
                  title: 'My Script',
                },
              };
              response = await gapi.client.script.projects.create(createRequest);
    
              const updateContentRequest = {
                scriptId: response.result.scriptId,
                resource: {
                  files: [{
                    name: 'hello',
                    type: 'SERVER_JS',
                    source: 'function helloWorld() {\n  console.log("Hello, world!");\n}',
                  }, {
                    name: 'appsscript',
                    type: 'JSON',
                    source: '{"timeZone":"America/New_York","' +
                       'exceptionLogging":"CLOUD"}',
                  }],
                },
              };
              response = await gapi.client.script.projects.updateContent(updateContentRequest);
              const output = `Script URL: https://script.google.com/d/${response.result.scriptId}/edit`;
              document.getElementById('content').innerText = output;
            } catch (err) {
              document.getElementById('content').innerText = err.message;
              return;
            }
          }
        </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 Apps Script API が呼び出されます。

次のステップ