JavaScript クイックスタート

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

クイックスタートでは、Google Workspace API を呼び出すアプリを設定して実行する方法について説明します。このクイックスタートでは、テスト環境に適した簡素化された認証方法を使用します。本番環境では、アプリに適したアクセス認証情報を選択する前に、認証と認可について学習することをおすすめします。

このクイックスタートでは、Google Workspace の推奨 API クライアント ライブラリを使用して、認証と認可フローの詳細を処理します。

目標

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

前提条件

  • Gmail が有効になっている Google アカウント。

環境の設定

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

API を有効にする

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

    API の有効化

OAuth 同意画面を構成する

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

  1. Google API Console で、メニュー > [Google Auth プラットフォーム] > [ブランディング] に移動します。

    [ブランディング] に移動

  2. Google Auth Platform をすでに構成している場合は、[ブランディング]、[対象]、[データアクセス] で次の OAuth 同意画面の設定を構成できます。「Google Auth Platform はまだ構成されていません」というメッセージが表示された場合は、[使ってみる] をクリックします。
    1. [アプリ情報] の [アプリ名] に、アプリの名前を入力します。
    2. [ユーザー サポートメール] で、ユーザーが同意について問い合わせる際に使用するサポートのメールアドレスを選択します。
    3. [続行] をクリックします。
    4. [対象] で [内部] を選択します。
    5. [続行] をクリックします。
    6. [連絡先情報] で、プロジェクトに対する変更の通知を受け取るメールアドレスを入力します。
    7. [続行] をクリックします。
    8. [完了] で、Google API サービスのユーザーデータに関するポリシーを確認し、同意する場合は [Google API サービス: ユーザーデータに関するポリシーに同意します] を選択します。
    9. [続行] をクリックします。
    10. [作成] をクリックします。
  3. 現時点では、スコープの追加をスキップできます。 今後、Google Workspace 組織外で使用するアプリを作成する場合は、[ユーザータイプ] を [外部] に変更する必要があります。次に、アプリに必要な認可スコープを追加します。詳細については、OAuth 同意画面を構成するガイドをご覧ください。

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

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

    [クライアント] に移動

  2. [Create Client] をクリックします。
  3. [アプリケーションの種類] > [ウェブ アプリケーション] をクリックします。
  4. [名前] フィールドに、認証情報の名前を入力します。この名前は Google Cloud コンソール にのみ表示されます。
  5. アプリに関連する承認済み URI を追加します。
    • クライアントサイド アプリ(JavaScript) - [承認済みの JavaScript 生成元] で [URI を追加] をクリックします。次に、ブラウザ リクエストに使用する URI を入力します。これにより、アプリケーションが OAuth 2.0 サーバーに API リクエストを送信できるドメインが識別されます。
    • サーバーサイド アプリ(Java、Python など) - [承認済みのリダイレクト URI] の下の [URI を追加] をクリックします。次に、OAuth 2.0 サーバーがレスポンスを送信するエンドポイント URI を入力します。
  6. 省略可: アプリがユーザーに代わってアクションを実践する AI エージェントの場合は、[このクライアントを AI 搭載エージェントに使用する] を選択します。アプリが AI エージェント ワークフローと標準ユーザー機能の両方をサポートしている場合は、それぞれに個別の OAuth クライアントを作成してください。クライアントの作成後にこの設定を変更することはできません。
  7. [Create] をクリックします。

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

    クライアント シークレットはウェブ アプリケーションでは使用されません。

  8. このクイックスタートの後半で使用するために、クライアント ID を保存します。

API キーを作成する

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

    [認証情報] に移動

  2. [認証情報を作成] > [API キー] をクリックします。
  3. 新しい API キーが表示されます。
    • コピーアイコン をクリックして API キーをコピーし、アプリのコードで使用します。API キーは、プロジェクトの認証情報の [API キー] セクションでも確認できます。
    • 不正使用を防ぐため、API キーを使用できる場所と対象の API を制限することをおすすめします。詳しくは、API 制限を追加するをご覧ください。

サンプルのセットアップ

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

    gmail/quickstart/index.html
    <!DOCTYPE html>
    <html>
      <head>
        <title>Gmail API Quickstart</title>
        <meta charset="utf>-8&<quot;> /
    <  /h>ead
     < >body
        pGmail API <Qu>icksta<rt/p
    
        !--Add buttons to initiate auth sequence and >sign <out--
        button id="authorize_button" onclick>="ha<ndleAut>hClic<k()"Authorize/button
        button id="signout_but>ton"<; oncli>ck=&qu<ot;handleSignoutClick()"Sign Out/button
    
     ><   p>re id=<"content" style=&qu>ot;white-space: pre-wrap;"/pre
    
        script type="text/javascript"
          /* exported gapiLoaded */
          /* exported gisLoaded */
          /* exported handleAuthClick */
          /* exported handleSignoutClick */
    
          // TODO(developer): S<et to client I>D and API key from the Dev<eloper Conso>le
          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/gmail/v1/rest';
    
          // Authorization scopes required by the API; multiple scopes can be
          // included, separated by spaces.
          const SCOPES = 'https://www.googleapis.com/auth/gmail.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 = 'vis>ible';
            }
          }
    
          /**
           *  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 listLabels();
            };
    
            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 all Labels in the authorized user's inbox. If no labels
           * are found an appropriate message is printed.
           */
          async function listLabels() {
            let response;
            try {
              response = await gapi.client.gmail.users.labels.list({
                'userId': 'me',
              });
            } catch (err) {
              document.getElementById('content').innerText = err.message;
              return;
       >     }
            const labels = response.result.labels;
            if (!labels || labels.length == 0) {
              document.getElemen<tById(&>#39;c<ontent').innerText = 'No labels found.';
              return;
            }><
          >  // <Flatten to string to display
            const output = labels.reduce(
                (str,>< label)> = <`${st>r<}${la>bel.name}\n`,
                'Labels:\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. アクセスを承認するよう求めるプロンプトが表示されます。
    1. Google アカウントにまだログインしていない場合は、プロンプトが表示されたらログインします。複数のアカウントにログインしている場合は、承認に使用するアカウントを 1 つ選択します。
    2. [Accept] をクリックします。

JavaScript アプリケーションが実行され、Gmail API が呼び出されます。

次のステップ