Google Apps Script 快速入門導覽課程

快速入門導覽課程說明如何設定及執行呼叫 Google Workspace API 的應用程式。

Google Workspace 快速入門導覽課程使用 API 用戶端程式庫處理驗證和授權流程的一些詳細資料。建議您在自己的應用程式中使用用戶端程式庫。本快速入門導覽課程採用適用於測試環境的簡化驗證方法。如果是實際工作環境,建議先瞭解驗證與授權,再選擇適合應用程式的存取憑證

建立 Google Apps Script,向 Google Classroom API 發出要求。

目標

  • 建立指令碼。
  • 啟用 Google Classroom API。
  • 執行範例。

必要條件

  • 擁有已啟用 Google Classroom 的 Google for Education 帳戶。

  • Google 雲端硬碟存取權

建立指令碼

  1. 前往 script.google.com/create 建立新的指令碼。
  2. 使用下列程式碼取代指令碼編輯器內容:

classroom/quickstart/quickstart.gs
/**
 * Lists 10 course names and ids.
 */
function listCourses() {
  /**  here pass pageSize Query parameter as argument to get maximum number of result
   * @see https://developers.google.com/classroom/reference/rest/v1/courses/list
   */
  const optionalArgs = {
    pageSize: 10
    // Use other parameter here if needed
  };
  try {
    // call courses.list() method to list the courses in classroom
    const response = Classroom.Courses.list(optionalArgs);
    const courses = response.courses;
    if (!courses || courses.length === 0) {
      console.log('No courses found.');
      return;
    }
    // Print the course names and IDs of the courses
    for (const course of courses) {
      console.log('%s (%s)', course.name, course.id);
    }
  } catch (err) {
    // TODO (developer)- Handle Courses.list() exception from Classroom API
    // get errors like PERMISSION_DENIED/INVALID_ARGUMENT/NOT_FOUND
    console.log('Failed with error %s', err.message);
  }
}

  1. 按一下「儲存」
  2. 按一下 [Untitled project] (未命名專案),輸入 quickstart,然後按一下 [Rename] (重新命名)

啟用 Google Classroom API

  1. 開啟 Apps Script 專案。
  2. 按一下「編輯器」
  3. 按一下「Services」旁邊的「新增服務」圖示
  4. 選取「Google Classroom API」,然後按一下「Add」

執行範例

在 Apps Script 編輯器中,按一下「執行」

首次執行範例時,系統會提示您授予存取權:

  1. 按一下「查看權限」
  2. 選擇所需帳戶。
  3. 按一下 [Allow]

指令碼的執行記錄會顯示在視窗底部。

後續步驟