Node.js クイックスタート

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

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

Drive Labels API にリクエストを送信する Node.js コマンドライン アプリケーションを作成します。

目標

  • 環境を設定する。
  • クライアント ライブラリをインストールする。
  • サンプルをセットアップします。
  • サンプルを実行します。

前提条件

  • Google アカウント

環境の設定

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

API を有効にする

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

デスクトップ アプリケーションの認証情報を承認する

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

    [認証情報] に移動

  2. [認証情報を作成] > [OAuth クライアント ID] をクリックします。
  3. [アプリケーションの種類] > [デスクトップ アプリ] をクリックします。
  4. [名前] フィールドに、認証情報の名前を入力します。この名前は Google Cloud コンソールにのみ表示されます。
  5. [作成] をクリックします。[OAuth クライアントの作成] 画面が表示され、新しいクライアント ID とクライアント シークレットが表示されます。
  6. [OK] をクリックします。新しく作成された認証情報が [OAuth 2.0 クライアント ID] に表示されます。
  7. ダウンロードした JSON ファイルを credentials.json として保存し、ファイルを作業ディレクトリに移動します。

クライアント ライブラリをインストールする

  • npm を使用してライブラリをインストールします。

    npm install googleapis@113 @google-cloud/local-auth@2.1.1 --save
    

サンプルのセットアップ

  1. 作業ディレクトリに、index.js という名前のファイルを作成します。

  2. このファイルに次のコードを貼り付けます。

        const fs = require('fs');
        const readline = require('readline');
        const {google} = require('googleapis');
    
        // If modifying these scopes, delete token.json.
        const SCOPES = ['https://www.googleapis.com/auth/drive.labels.readonly'];
        // The file token.json stores the user's access and refresh tokens, and is
        // created automatically when the authorization flow completes for the first
        // time.
        const TOKEN_PATH = 'token.json';
    
        // Load client secrets from a local file.
        fs.readFile('credentials.json', (err, content) => {
          if (err) return console.log('Error loading client secret file:', err);
          // Authorize a client with credentials, then call the Google Drive Labels
          // API.
          authorize(JSON.parse(content), listDriveLabels);
        });
    
        /**
        * Create an OAuth2 client with the given credentials, and then execute the
        * given callback function.
        * @param {Object} credentials The authorization client credentials.
        * @param {function} callback The callback to call with the authorized client.
        */
        function authorize(credentials, callback) {
          const {client_secret, client_id, redirect_uris} = credentials.installed;
          const oAuth2Client = new google.auth.OAuth2(
              client_id, client_secret, redirect_uris[0]);
    
          // Check if we have previously stored a token.
          fs.readFile(TOKEN_PATH, (err, token) => {
            if (err) return getNewToken(oAuth2Client, callback);
            oAuth2Client.setCredentials(JSON.parse(token));
            callback(oAuth2Client);
          });
        }
    
        /**
        * Get and store new token after prompting for user authorization, and then
        * execute the given callback with the authorized OAuth2 client.
        * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
        * @param {getEventsCallback} callback The callback for the authorized client.
        */
        function getNewToken(oAuth2Client, callback) {
          const authUrl = oAuth2Client.generateAuthUrl({
            access_type: 'offline',
            scope: SCOPES,
          });
          console.log('Authorize this app by visiting this url:', authUrl);
          const rl = readline.createInterface({
            input: process.stdin,
            output: process.stdout,
          });
          rl.question('Enter the code from that page here: ', (code) => {
            rl.close();
            oAuth2Client.getToken(code, (err, token) => {
              if (err) return console.error('Error retrieving access token', err);
              oAuth2Client.setCredentials(token);
              // Store the token to disk for later program executions
              fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
                if (err) return console.error(err);
                console.log('Token stored to', TOKEN_PATH);
              });
              callback(oAuth2Client);
            });
          });
        }
    
        function listDriveLabels(auth) {
          const service = google.drivelabels({version: 'v2', auth});
          const params = {
            'view': 'LABEL_VIEW_FULL'
          };
          service.labels.list(params, (err, res) => {
            if (err) return console.error('The API returned an error: ' + err);
            const labels = res.data.labels;
            if (labels) {
              labels.forEach((label) => {
                const name = label.name;
                const title = label.properties.title;
                console.log(`${name}\t${title}`);
              });
            } else {
              console.log('No Labels');
            }
          });
        }
    

サンプルの実行

  1. 作業ディレクトリでサンプルを実行します。

    node .
    
  2. サンプルを初めて実行すると、アクセスの承認を求められます。

    1. Google アカウントにまだログインしていない場合は、ログインを求められます。複数のアカウントにログインしている場合は、認証に使用するアカウントを 1 つ選択します。
    2. [Accept] をクリックします。

    認可情報はファイル システムに保存されるため、サンプルコードを次回実行するときに、認可を求められません。

Drive Labels API にリクエストを送信する最初の Nodejs アプリケーションが正常に作成されました。

次のステップ