本頁說明如何存取 Classroom API 搶先版功能,以及如何指定搶先版。
與穩定版 v1 API 相比,使用預先發布版功能時有三項注意事項:
- 呼叫的 Google Cloud 專案必須註冊 Google Workspace 開發人員搶先體驗計畫,並由 Google 列入許可清單。
 - 搶先體驗或預先發布計畫中的 API 功能不會顯示在標準用戶端程式庫中,且可能無法透過 HTTP 預設存取。
 - 在任何特定時間內,可能有多個 API 狀態或版本處於預覽階段。
 
在用戶端程式庫中啟用預先發布功能
如要使用 Classroom API,常見的做法是透過用戶端程式庫。用戶端程式庫分為三種類型:
- 動態產生的用戶端程式庫
 - Google 提供的靜態用戶端程式庫
 - 您自己的自訂用戶端程式庫
 
建議使用動態產生或 Google 提供的靜態程式庫來使用 API。如需建構自己的程式庫,請參閱建構用戶端程式庫。本指南不會說明如何建立自己的程式庫,但建議您查看「動態程式庫」一節,瞭解預覽標籤及其在探索中的作用。
動態程式庫
Python 等語言的程式庫會在執行階段使用探索服務的探索文件,產生用戶端程式庫。
探索文件是一種機器可解讀的規格,用於說明和使用 REST API。此文件用於建構用戶端程式庫、IDE 外掛程式,以及與 Google API 互動的其他工具。一項服務可能會提供多個探索文件。
Classroom API 服務的探索文件 (classroom.googleapis.com) 位於下列端點:
https://classroom.googleapis.com/$discovery/rest?labels=PREVIEW_LABEL&version=v1&key=API_KEY
使用預覽版 API 時,重要區別在於指定適當的 label。Classroom 公開測試版的標籤為 DEVELOPER_PREVIEW。
如要產生 Python 程式庫,並使用預覽方法例項化 Classroom 服務,您可以指定 Discovery 網址,並提供適當的服務、憑證和標籤:
classroom_service_with_preview_features = googleapiclient.discovery.build(
  serviceName='classroom',
  version='v1',
  credentials=credentials,
  static_discovery=False,
  discoveryServiceUrl='https://classroom.googleapis.com/$discovery/rest?labels=DEVELOPER_PREVIEW&key=API_KEY)'
如要瞭解各語言的詳細資料,請參閱個別 Google API 的用戶端程式庫說明文件。
靜態程式庫
您必須從來源建構 Java、Node.js、PHP、C# 和 Go 等語言的用戶端程式庫。這些程式庫已為您提供,並已納入預先發布功能。
公開預覽版發布後,您可以在其他 Workspace 開發人員預覽版計畫用戶端程式庫中找到 Classroom 用戶端程式庫。如需產生靜態程式庫,請洽詢您的 Google 聯絡窗口。
您可能需要修改一般依附元件設定,才能使用這些本機程式庫,而不是匯入沒有預覽功能的標準用戶端程式庫。
舉例來說,如要使用 Go 用戶端程式庫,您需要在 go.mod 檔案中使用 replace 指令,從本機目錄要求模組:
module example.com/app
go 1.21.1
require (
    golang.org/x/oauth2 v0.12.0
    google.golang.org/api v0.139.0 // Classroom library is in here.
)
require (
  ...
)
// Use a local copy of the Go client library.
replace google.golang.org/api v0.139.0 => ../google-api-go-client
以 Node.js 和 npm 為例,請將 Node.js 用戶端程式庫下載 (googleapis-classroom-1.0.4.tgz) 新增為 package.json 中的本機依附元件:
{
  "name": "nodejs-classroom-example",
  "version": "1.0.0",
  ...
  "dependencies": {
    "@google-cloud/local-auth": "^2.1.0",
    "googleapis": "^95.0.0",
    "classroom-with-preview-features": "file:./googleapis-classroom-1.0.4.tgz"
  }
}
接著,在應用程式中,除了正規依附元件外,還需要 classroom-with-preview-features 模組,並從該模組例項化 classroom 服務:
const {authenticate} = require('@google-cloud/local-auth');
const {google} = require('googleapis');
const classroomWithPreviewFeatures = require('classroom-with-preview-features');
...
const classroom = classroomWithPreviewFeatures.classroom({
  version: 'v1',
  auth: auth,
});
...
指定預覽版 API 版本
無論使用靜態或動態程式庫,您都必須在呼叫具有預覽功能的方法時,指定預覽版本。
如要瞭解各個可用版本及其包含的功能,請參閱 Classroom API 發展藍圖。方法和欄位的參考說明文件也會說明方法或欄位適用的版本。
如要指定版本,請在要求中設定 PreviewVersion 欄位。
舉例來說,如要使用 Rubrics CRUD 預覽版 API 建立評量表,請在 CREATE 要求中將 previewVersion 設為 V1_20231110_PREVIEW:
rubric = service.courses().courseWork().rubrics().create(
            courseId=course_id,
            courseWorkId=coursework_id,
            # Specify the preview version. Rubrics CRUD capabilities are
            # supported in V1_20231110_PREVIEW and later.
            previewVersion="V1_20231110_PREVIEW",
            body=body
).execute()
與預覽方法呼叫相關聯的資源也會包含呼叫中使用的 previewVersion 做為唯讀欄位,協助您瞭解使用的版本。舉例來說,先前 CREATE 呼叫的回應包含 V1_20231110_PREVIEW 值:
print(json.dumps(rubric, indent=4))
{
  "courseId": "123",
  "courseWorkId": "456",
  "creationTime": "2023-10-23T18:18:29.932Z",
  "updateTime": "2023-10-23T18:18:29.932Z",
  "id": "789",
  "criteria": [...],
  # The preview version used in the call that returned this resource.
  "previewVersion": "V1_20231110_PREVIEW",
  ...
}
HTTP 要求
您也可以直接透過 HTTP 使用 Classroom API。
如果您在沒有用戶端程式庫的情況下發出 HTTP 要求,仍須啟用預覽功能並指定預覽版本。方法是設定 label,並使用 X-Goog-Visibilities 標頭和上述預覽版本做為查詢參數或 POST 主體欄位 (請參閱適當的個別 API 參考文件)。公開預先發布版會顯示 DEVELOPER_PREVIEW 標籤。
舉例來說,下列 curl 要求會使用適當的顯示標籤和預覽版本,向 Rubrics 服務發出 LIST 呼叫:
curl \
  'https://classroom.googleapis.com/v1/courses/COURSE_ID/courseWork/COURSE_WORK_ID/rubrics?key=API_KEY&previewVersion=V1_20231110_PREVIEW' \
  --header 'X-Goog-Visibilities: DEVELOPER_PREVIEW' \
  --header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
  --header 'Accept: application/json' \
  --compressed您也可以在要求主體中指定預覽版本,例如發出 POST 要求時:
curl --request PATCH \
  'https://classroom.googleapis.com/v1/courses/COURSE_ID/courseWork/COURSE_WORK_ID/rubrics/RUBRIC_ID?updateMask=criteria&key=API_KEY&previewVersion=V1_20231110_PREVIEW' \
  --header 'X-Goog-Visibilities: DEVELOPER_PREVIEW' \
  --header 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
  --header 'Accept: application/json' \
  --header 'Content-Type: application/json' \
  --data '{"criteria":"[...]"}' \
  --compressedREST 說明文件會說明每個 HTTP 要求的 API。
Google Apps Script
您可以透過 Google Apps Script 呼叫預覽版 API。不過,這與一般 Apps Script 用法有幾項差異。
- 您必須將指令碼設定為使用您在開發人員搶先體驗計畫中註冊的 Google Cloud 專案。
 - 進階服務不支援預覽方法,因此您需要直接透過 HTTP 提出要求。
 - 您必須提供標籤和預覽版本,如前一節的 HTTP 說明所述。
 
請參閱對應的快速入門導覽課程,熟悉 Apps Script 並設定基本專案。然後按照下列操作說明,開始使用通話預覽版 API:
變更指令碼使用的 Cloud 專案
在「專案設定」中,按一下「變更專案」,然後輸入您註冊開發人員搶先體驗計畫的專案 Cloud 專案 ID (根據預設,Apps Script 指令碼會使用一般專案)。只有已註冊的專案可以呼叫預覽方法。
設定 HTTP 要求
接著,在「編輯器」中,設定要呼叫的方法的 HTTP 要求。舉例來說,在快速入門導覽課程中,使用 Classroom 服務列出課程的程式碼如下:
function listCourses() {
  try {
    const response = Classroom.Courses.list();
    const courses = response.courses;
    if (!courses || courses.length === 0) {
      console.log('No courses found.');
      return;
    }
    for (const course of courses) {
      console.log('%s (%s)', course.name, course.id);
    }
  } catch (err) {
    // TODO: Developer to handle.
    console.log(err.message);
  }
}
直接使用 HTTP 的對等作業如下:
function listCourses() {
  const response = UrlFetchApp.fetch(
        'https://classroom.googleapis.com/v1/courses', {
        method: 'GET',
        headers: {'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},
        contentType: 'application/json',
      });
  const data = JSON.parse(response.getContentText());
  if (data.error) {
    // TODO: Developer to handle.
    console.log(err.message);
    return;
  }
  if (!data.courses || !data.courses.length) {
    console.log('No courses found.');
    return;
  }
  for (const course of data.courses) {
    console.log('%s (%s)', course.name, course.id);
  }
}
使用進階服務時,系統會推斷必要的 OAuth 範圍,但如要在 Apps Script 中直接對 Google API 進行 HTTP 呼叫,您必須手動新增適當的範圍。
在「專案設定」中,啟用「在編輯器中顯示『appsscript.json』資訊清單檔案」。返回「編輯器」,在 appscript.json 檔案中新增 oauthScopes,並視需要設定範圍。特定方法的範圍會列在參考頁面中。舉例來說,請參閱課程.courseWork.rubrics 清單方法頁面。
更新後的 appscript.json 檔案可能如下所示:
{
  "timeZone": "America/Los_Angeles",
  "dependencies": {
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8",
  "oauthScopes": [
    "https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/classroom.coursework.students",
    "https://www.googleapis.com/auth/classroom.courses",
    "https://www.googleapis.com/auth/spreadsheets.readonly",
    "https://www.googleapis.com/auth/spreadsheets"
  ]
}
提供標籤和預覽版本
回到指令碼,確認您已如先前 HTTP 區段所述,新增適當的標籤和預覽版本。以下是傳送至 Rubrics 服務的 LIST 呼叫範例:
function listRubrics() {
  const courseId = COURSE_ID;
  const courseWorkId = COURSE_WORK_ID;
  const response = UrlFetchApp.fetch(
         `https://classroom.googleapis.com/v1/courses/${courseId}/courseWork/${courseWorkId}/rubrics?previewVersion=V1_20231110_PREVIEW`, {
        method: 'GET',
        headers: {
          'Authorization': 'Bearer ' + ScriptApp.getOAuthToken(),
          'X-Goog-Visibilities': 'DEVELOPER_PREVIEW'
        },
        contentType: 'application/json',
        muteHttpExceptions: true
      });
  const data = JSON.parse(response.getContentText());
  console.log(data)
  if (data.error) {
    // TODO: Developer to handle.
    console.log(error.message);
    return;
  }
  if (!data.rubrics || !data.rubrics.length) {
    console.log('No rubrics for this coursework!');
    return;
  }
  console.log(data.rubrics);
}