クイックスタートでは、Google Workspace API を呼び出すアプリを設定して実行する方法について説明します。
Google Workspace のクイックスタートでは、API クライアント ライブラリを使用して、認証と承認フローの詳細の一部を処理します。ご自身でアプリを開発する際には、このクライアント ライブラリを使用することをおすすめします。このクイックスタートでは、テスト環境に適した簡素な認証方法を使用します。本番環境では、アプリに適したアクセス認証情報を選択する前に、認証と承認について学習することをおすすめします。
Drive Labels API にリクエストを送信する Node.js コマンドライン アプリケーションを作成します。
目標
- 環境をセットアップする。
- クライアント ライブラリをインストールする。
- サンプルを設定します。
- サンプルを実行します。
前提条件
- Node.js と npm がインストールされている。
- Google Cloud プロジェクト。
- Google アカウント。
環境の設定
このクイックスタートを完了するには、環境を設定します。
API を有効にする
Google API を使用する前に、Google Cloud プロジェクトで API を有効にする必要があります。1 つの Google Cloud プロジェクトで 1 つ以上の API を有効にできます。Google Cloud コンソールで、Drive Labels API を有効にします。
デスクトップ アプリケーションの認証情報を承認する
エンドユーザーを認証し、アプリ内のユーザーデータにアクセスするには、1 つ以上の OAuth 2.0 クライアント ID を作成する必要があります。クライアント ID は、Google の OAuth サーバーで個々のアプリを識別するために使用します。アプリが複数のプラットフォームで実行される場合は、プラットフォームごとに個別のクライアント ID を作成する必要があります。- Google Cloud コンソールで、メニュー > > [クライアント] に移動します。
- [Create Client] をクリックします。
- [アプリケーションの種類] > [デスクトップ アプリ] をクリックします。
- [名前] フィールドに、認証情報の名前を入力します。この名前は Google Cloud コンソールにのみ表示されます。
- [Create] をクリックします。
新しく作成された認証情報が [OAuth 2.0 クライアント ID] の下に表示されます。
- ダウンロードした JSON ファイルを
credentials.json
として保存し、ファイルを作業ディレクトリに移動します。
クライアント ライブラリをインストールする
npm を使用してライブラリをインストールします。
npm install googleapis@113 @google-cloud/local-auth@2.1.1 --save
サンプルのセットアップ
作業ディレクトリに
index.js
という名前のファイルを作成します。ファイルに次のコードを貼り付けます。
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'); } }); }
サンプルの実行
作業ディレクトリでサンプルを実行します。
node .
サンプルを初めて実行すると、アクセスを承認するよう求められます。
- Google アカウントにログインしていない場合は、ログインを求められます。複数のアカウントにログインしている場合は、承認に使用するアカウントを 1 つ選択します。
- [Accept] をクリックします。
認証情報はファイル システムに保存されるため、サンプルコードを次回実行するときに認証を求められることはありません。
これで、Drive Labels API にリクエストを送信する最初の Nodejs アプリケーションが作成されました。