管理老師和學生

師生是使用者設定檔與課程之間的具體對應項目,代表使用者在課程中扮演的角色。學生和老師屬於非全球性:您可以將某位使用者指派為一門課程的老師,以及另一門課程的學生。標示「學生」或「老師」代表特定課程中特定使用者的一組權限。

學生
學生資源代表以學生的身分註冊特定課程。學生可以查看該課程的詳細資料和老師。
教師
教師資源代表教授特定課程的使用者。老師有權查看及變更課程詳細資料、查看老師和學生,以及管理其他老師和學生。

學生和老師會依使用者的專屬 ID 或電子郵件地址來識別,此 ID 是由 Directory API 傳回。目前使用者也可以使用 "me" 簡寫參照自己的 ID。

直接新增

網域管理員可以略過邀請流程,並直接將他們網域中的使用者新增為網域中老師或學生。如果課程的擁有者在管理員網域中,則課程會在管理員網域中被視為。對於已驗證網域管理員網域以外的使用者或課程,應用程式必須透過 invitations.create() 方法傳送邀請,藉此取得使用者的同意。

新增或移除老師

網域管理員可以直接將自身網域中的老師新增至使用 teachers.create() 的課程,如以下範例所示:

.NET

classroom/snippets/ClassroomSnippets/AddTeacher.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Classroom.v1;
using Google.Apis.Classroom.v1.Data;
using Google.Apis.Services;
using System;
using System.Net;
using Google;

namespace ClassroomSnippets
{
    // Class to demonstrate the use of Classroom Create Teacher API
    public class AddTeacher
    {
       /// <summary>
       /// Add teacher to the Course
       /// </summary>
       /// <param name="courseId"></param>
       /// <param name="teacherEmail"></param>
       /// <returns></returns>
        public static Teacher ClassroomAddTeacher( string courseId,
                 string teacherEmail)
         {
             try 
             {
                 /* Load pre-authorized user credentials from the environment.
                  TODO(developer) - See https://developers.google.com/identity for 
                  guides on implementing OAuth2 for your application. */
                 GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                     .CreateScoped(ClassroomService.Scope.ClassroomRosters);

                 // Create Classroom API service.
                 var service = new ClassroomService(new BaseClientService.Initializer
                 {
                     HttpClientInitializer = credential,
                     ApplicationName = "Classroom API Snippet"
                 });

                 var teacher = new Teacher
                 {
                     UserId = teacherEmail
                 };
                 // Add the teacher to the course.
                 teacher = service.Courses.Teachers.Create(teacher, courseId).Execute();
                     Console.WriteLine(
                         "User '{0}' was added as a teacher to the course with ID '{1}'.\n",
                         teacher.Profile.Name.FullName, courseId);
                     return teacher;
             }
             catch (Exception e)
             {
                 // TODO(developer) - handle error appropriately
                 if (e is AggregateException)
                 {
                     Console.WriteLine("Credential Not found");
                 }
                 else if (e is GoogleApiException)
                 {
                     Console.WriteLine("Failed to Add the teacher. Error message: {0}", e.Message);
                 }
                 else
                 {
                     throw;
                 }
             }

             return null;
         }


    }

}

Java

classroom/snippets/src/main/java/AddTeacher.java
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.classroom.Classroom;
import com.google.api.services.classroom.ClassroomScopes;
import com.google.api.services.classroom.model.Teacher;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;

/* Class to demonstrate the use of Classroom Add Teacher API */
public class AddTeacher {

  /* Scopes required by this API call. If modifying these scopes, delete your previously saved
  tokens/ folder. */
  static ArrayList<String> SCOPES =
      new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_ROSTERS));

  /**
   * Add teacher to a specific course.
   *
   * @param courseId - Id of the course.
   * @param teacherEmail - Email address of the teacher.
   * @return newly created teacher
   * @throws IOException - if credentials file not found.
   * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created.
   */
  public static Teacher addTeacher(String courseId, String teacherEmail)
      throws GeneralSecurityException, IOException {

    // Create the classroom API client.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    Classroom service =
        new Classroom.Builder(
                HTTP_TRANSPORT,
                GsonFactory.getDefaultInstance(),
                ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES))
            .setApplicationName("Classroom samples")
            .build();

    Teacher teacher = new Teacher().setUserId(teacherEmail);
    try {
      // Add a teacher to a specified course
      teacher = service.courses().teachers().create(courseId, teacher).execute();
      // Prints the course id with the teacher name
      System.out.printf(
          "User '%s' was added as a teacher to the course with ID '%s'.\n",
          teacher.getProfile().getName().getFullName(), courseId);
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      GoogleJsonError error = e.getDetails();
      if (error.getCode() == 409) {
        System.out.printf("User '%s' is already a member of this course.\n", teacherEmail);
      } else if (error.getCode() == 403) {
        System.out.println("The caller does not have permission.\n");
      } else {
        throw e;
      }
    }
    return teacher;
  }
}

PHP

classroom/snippets/src/ClassroomAddTeacher.php
use Google\Client;
use Google\Service\Classroom;
use Google\Service\Classroom\Teacher;
use Google\service\Exception;

function addTeacher($courseId, $teacherEmail)
{
    /* Load pre-authorized user credentials from the environment.
    TODO (developer) - See https://developers.google.com/identity for
     guides on implementing OAuth2 for your application. */
    $client = new Client();
    $client->useApplicationDefaultCredentials();
    $client->addScope("https://www.googleapis.com/auth/classroom.profile.photos");
    $service = new Classroom($client);
    $teacher = new Teacher([
        'userId' => $teacherEmail
    ]);
    try {
        //  calling create teacher
        $teacher = $service->courses_teachers->create($courseId, $teacher);
        printf("User '%s' was added as a teacher to the course with ID '%s'.\n",
            $teacher->profile->name->fullName, $courseId);
    } catch (Exception $e) {
        if ($e->getCode() == 409) {
            printf("User '%s' is already a member of this course.\n", $teacherEmail);
        } else {
            throw $e;
        }
    }
    return $teacher;
}

Python

classroom/snippets/classroom_add_Teacher.py
import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def classroom_add_teacher(course_id):
  """
  Adds a teacher to a course with specific course_id.
  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity
  for guides on implementing OAuth2 for the application.
  """
  creds, _ = google.auth.default()
  # pylint: disable=maybe-no-member
  service = build("classroom", "v1", credentials=creds)

  teacher_email = "gduser1@workspacesamples.dev"
  teacher = {"userId": teacher_email}

  try:
    teachers = service.courses().teachers()
    teacher = teachers.create(courseId=course_id, body=teacher).execute()
    print(
        "User %s was added as a teacher to the course with ID %s"
        % (teacher.get("profile").get("name").get("fullName"), course_id)
    )
  except HttpError as error:
    print('User "{%s}" is already a member of this course.' % teacher_email)
    return error
  return teachers


if __name__ == "__main__":
  # Put the course_id of course for which Teacher needs to be added.
  classroom_add_teacher(453686957652)

如果您要代表通過驗證的老師新增其他老師,就必須使用 invitations.create() 方法。

您可以使用 teachers.delete() 方法移除課程中的其他老師。這麼做只會將指定老師從課程中移除,並不影響他們指派給其他課程或其使用者個人資料。

註冊或移除學生

網域管理員可以使用 students.create() 方法,直接將學生加入網域中的學生,如以下範例所示:

.NET

classroom/snippets/ClassroomSnippets/AddStudent.cs
using Google.Apis.Auth.OAuth2;
using Google.Apis.Classroom.v1;
using Google.Apis.Classroom.v1.Data;
using Google.Apis.Services;
using System;
using System.Net;
using Google;

namespace ClassroomSnippets
{
    // Class to demonstrate the use of Classroom Create Student API
    public class AddStudent
    {
        public static Student ClassroomAddStudent(string courseId, string enrollmentCode)
        {
            try
            {
                /* Load pre-authorized user credentials from the environment.
                 TODO(developer) - See https://developers.google.com/identity for 
                 guides on implementing OAuth2 for your application. */
                GoogleCredential credential = GoogleCredential.GetApplicationDefault()
                    .CreateScoped(ClassroomService.Scope.ClassroomRosters);
                var service = new ClassroomService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Classroom API .NET Quickstart"
                });

                var student = new Student
                {
                    UserId = "me"
                };

                var request = service.Courses.Students.Create(student, courseId);
                request.EnrollmentCode = enrollmentCode;
                student = request.Execute();
                Console.WriteLine(
                    "User '{0}' was enrolled  as a student in the course with ID '{1}'.\n",
                    student.Profile.Name.FullName, courseId);
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else if (e is GoogleApiException)
                {
                    Console.WriteLine("Failed to Add the Student. Error message: {0}", e.Message);
                }
                else
                {
                    throw;
                }
            }

            return null;
        }
    }

}

Java

classroom/snippets/src/main/java/AddStudent.java
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.classroom.Classroom;
import com.google.api.services.classroom.ClassroomScopes;
import com.google.api.services.classroom.model.Student;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;

/* Class to demonstrate the use of Classroom Add Student API */
public class AddStudent {

  /* Scopes required by this API call. If modifying these scopes, delete your previously saved
  tokens/ folder. */
  static ArrayList<String> SCOPES =
      new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_ROSTERS));

  /**
   * Add a student in a specified course.
   *
   * @param courseId - Id of the course.
   * @param enrollmentCode - Code of the course to enroll.
   * @return newly added student
   * @throws IOException - if credentials file not found.
   * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created.
   */
  public static Student addStudent(String courseId, String enrollmentCode, String studentId)
      throws GeneralSecurityException, IOException {

    // Create the classroom API client.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    Classroom service =
        new Classroom.Builder(
                HTTP_TRANSPORT,
                GsonFactory.getDefaultInstance(),
                ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES))
            .setApplicationName("Classroom samples")
            .build();

    Student student = new Student().setUserId(studentId);
    try {
      // Enrolling a student to a specified course
      student =
          service
              .courses()
              .students()
              .create(courseId, student)
              .setEnrollmentCode(enrollmentCode)
              .execute();
      // Prints the course id with the Student name
      System.out.printf(
          "User '%s' was enrolled as a student in the course with ID '%s'.\n",
          student.getProfile().getName().getFullName(), courseId);
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      GoogleJsonError error = e.getDetails();
      if (error.getCode() == 409) {
        System.out.println("You are already a member of this course.");
      } else if (error.getCode() == 403) {
        System.out.println("The caller does not have permission.\n");
      } else {
        throw e;
      }
    }
    return student;
  }
}

PHP

classroom/snippets/src/ClassroomAddStudent.php
use Google\Client;
use Google\Service\Classroom;
use Google\Service\Classroom\Student;
use Google\Service\Exception;

function enrollAsStudent($courseId,$enrollmentCode)
{
    /* Load pre-authorized user credentials from the environment.
    TODO (developer) - See https://developers.google.com/identity for
     guides on implementing OAuth2 for your application. */
    $client = new Client();
    $client->useApplicationDefaultCredentials();
    $client->addScope("https://www.googleapis.com/auth/classroom.profile.emails");
    $service = new Classroom($client);
    $student = new Student([
        'userId' => 'me'
    ]);
    $params = [
        'enrollmentCode' => $enrollmentCode
    ];
    try {
        $student = $service->courses_students->create($courseId, $student, $params);
        printf("User '%s' was enrolled  as a student in the course with ID '%s'.\n",
            $student->profile->name->fullName, $courseId);
    } catch (Exception $e) {
        if ($e->getCode() == 409) {
            print "You are already a member of this course.\n";
        } else {
            throw $e;
        }
    }
    return $student;
}

Python

classroom/snippets/classroom_add_student.py
import os

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

SCOPES = ["https://www.googleapis.com/auth/classroom.coursework.students"]


def classroom_add_student_new(course_id):
  """
  Adds a student to a course, the teacher has access to.
  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.
  Load pre-authorized user credentials from the environment.
  TODO(developer) - See https://developers.google.com/identity for
   guides on implementing OAuth2 for the application.
  """

  creds = None
  # 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.
  if os.path.exists("token.json"):
    creds = Credentials.from_authorized_user_file("token.json", SCOPES)
  # 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.json", "w", encoding="utf8") as token:
      token.write(creds.to_json())

  enrollment_code = "abc-def"
  student = {"userId": "gduser1@workspacesamples.dev"}
  try:
    service = build("classroom", "v1", credentials=creds)
    student = (
        service.courses()
        .students()
        .create(
            courseId=course_id, enrollmentCode=enrollment_code, body=student
        )
        .execute()
    )
    print(
        '''User {%s} was enrolled as a student in
                   the course with ID "{%s}"'''
        % (student.get("profile").get("name").get("fullName"), course_id)
    )
    return student
  except HttpError as error:
    print(error)
    return error


if __name__ == "__main__":
  # Put the course_id of course for which student needs to be added.
  classroom_add_student_new(478800920837)

如果您要代表通過驗證的老師新增學生,則必須使用 invitations.create() 方法。

您可以使用 students.delete() 方法將學生從課程中移除。這麼做只會將指定學生從課程中移除,不會影響該學生在其他課程的註冊狀態或其使用者個人資料。

擷取使用者的課程

如要擷取學生或老師的課程清單,請呼叫 courses.list(),並提供對應的使用者的 studentIdteacherId

擷取使用者的個人資料

如要擷取使用者的橋接設定檔 (包括 ID 和姓名),請使用使用者 ID、電子郵件地址或「me」來為提出要求的使用者呼叫 userProfiles.get()

如要擷取 emailAddress 欄位,您必須加入 classroom.profile.emails 範圍。

傳回的 ID 會對應至包含相符 studentIdteacherIdDirectory API 使用者資源

管理課程擁有者

網域管理員可在不同老師之間轉移課程擁有權。如要瞭解重要詳細資訊,請參閱轉移課程擁有權一節。