如何获取 Google 课堂 API 的课程 ID

How to get the course ID for Google Classroom API

我正在尝试使用 Google Classroom API, I've read through their documentation,课程 ID 基本上用于所有内容,但他们从未解释在哪里可以找到课程的课程 ID。

似乎在您创建课程时,该函数会 return 课程 ID,但我想知道是否可以获取已经存在的课程的课程 ID。

如文档的快速入门页面 (https://developers.google.com/classroom/quickstart/python) 所示,您可以 运行 一段代码列出用户可以使用其凭据访问的前 10 个课程。然后,您可以在遍历课程时添加 print(course['id']) 语句以打印您检索到的课程的 ID。 python 示例如下所示

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly']

def main():
    """Shows basic usage of the Classroom API.
    Prints the names of the first 10 courses the user has access to.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('classroom', 'v1', credentials=creds)

    # Call the Classroom API
    results = service.courses().list(pageSize=10).execute()
    courses = results.get('courses', [])

    if not courses:
        print('No courses found.')
    else:
        print('Courses:')
        for course in courses:
            print(course['name'])
            print(course['id'])

if __name__ == '__main__':
    main()

我在nodejs/javascript中使用它来检索所有教室

const { google } = require("googleapis");
const classroom = google.classroom('v1');
const SCOPES = [
  "https://www.googleapis.com/auth/classroom.rosters",
  "https://www.googleapis.com/auth/classroom.profile.emails",
  "https://www.googleapis.com/auth/classroom.profile.photos",
  "https://www.googleapis.com/auth/classroom.courses"
];
google.options({
  auth: client,
});
//retrieve all classroom
async function getClassroom() {
  try {
    const res = await classroom.courses.list(
      // {
      //   pageSize: 10,
      //   pageToken: "",
      // }
    );
    console.log(res.data, "res");
  } catch (error) {
    console.error("Error:", error.message,);
  }
}

注意:客户端是我首选的授权方式