Node.js クイックスタート

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

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

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

目標

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

前提条件

このクイックスタートを実行するには、次の前提条件を満たす必要があります。

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

環境を設定する

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

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. [作成] をクリックします。[OAuth クライアントの作成] 画面が表示され、新しいクライアント ID とクライアント シークレットが表示されます。
  6. [OK] をクリックします。新しく作成された認証情報が [OAuth 2.0 クライアント ID] に表示されます。
  7. ダウンロードした JSON ファイルを credentials.json として保存し、ファイルを作業ディレクトリに移動します。

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

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

    npm install googleapis@95 @google-cloud/local-auth@2.1.0 --save
    

サンプルのセットアップ

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

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

    classroom/quickstart/index.js
    const fs = require('fs').promises;
    const path = require('path');
    const process = require('process');
    const {authenticate} = require('@google-cloud/local-auth');
    const {google} = require('googleapis');
    
    // If modifying these scopes, delete token.json.
    const SCOPES = ['https://www.googleapis.com/auth/classroom.courses.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 = path.join(process.cwd(), 'token.json');
    const CREDENTIALS_PATH = path.join(process.cwd(), 'credentials.json');
    
    /**
     * Reads previously authorized credentials from the save file.
     *
     * @return {Promise<OAuth2Client|null>}
     */
    async function loadSavedCredentialsIfExist() {
      try {
        const content = await fs.readFile(TOKEN_PATH);
        const credentials = JSON.parse(content);
        return google.auth.fromJSON(credentials);
      } catch (err) {
        return null;
      }
    }
    
    /**
     * Serializes credentials to a file compatible with GoogleAuth.fromJSON.
     *
     * @param {OAuth2Client} client
     * @return {Promise<void>}
     */
    async function saveCredentials(client) {
      const content = await fs.readFile(CREDENTIALS_PATH);
      const keys = JSON.parse(content);
      const key = keys.installed || keys.web;
      const payload = JSON.stringify({
        type: 'authorized_user',
        client_id: key.client_id,
        client_secret: key.client_secret,
        refresh_token: client.credentials.refresh_token,
      });
      await fs.writeFile(TOKEN_PATH, payload);
    }
    
    /**
     * Load or request or authorization to call APIs.
     *
     */
    async function authorize() {
      let client = await loadSavedCredentialsIfExist();
      if (client) {
        return client;
      }
      client = await authenticate({
        scopes: SCOPES,
        keyfilePath: CREDENTIALS_PATH,
      });
      if (client.credentials) {
        await saveCredentials(client);
      }
      return client;
    }
    
    /**
     * Lists the first 10 courses the user has access to.
     *
     * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
     */
    async function listCourses(auth) {
      const classroom = google.classroom({version: 'v1', auth});
      const res = await classroom.courses.list({
        pageSize: 10,
      });
      const courses = res.data.courses;
      if (!courses || courses.length === 0) {
        console.log('No courses found.');
        return;
      }
      console.log('Courses:');
      courses.forEach((course) => {
        console.log(`${course.name} (${course.id})`);
      });
    }
    
    authorize().then(listCourses).catch(console.error);

サンプルの実行

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

    node .
    
  1. サンプルを初めて実行すると、アクセスの承認を求められます。
    1. Google アカウントにまだログインしていない場合は、ログインを求められたらログインします。複数のアカウントにログインしている場合は、認証に使用するアカウントを 1 つ選択してください。
    2. [Accept] をクリックします。

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

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

次のステップ