Tạo và quản lý giáo viên và học viên

Vai trò của học viên và giáo viên trong Google Lớp học thể hiện vai trò của người dùng trong một khoá học. Một người dùng có thể được chỉ định làm giáo viên trong một khoá học và làm học viên trong một khoá học khác. Chức danh "học viên" hoặc "giáo viên" đại diện cho một nhóm quyền cho một người dùng cụ thể trong một khoá học cụ thể.

Sinh viên
Tài nguyên Student đại diện cho một người dùng đăng ký làm học viên trong một khoá học cụ thể. Học viên được phép xem thông tin chi tiết về khoá học và giáo viên của khoá học đó.
Giáo viên
Tài nguyên Teacher đại diện cho một người dùng dạy một khoá học cụ thể. Giáo viên được phép xem và thay đổi thông tin chi tiết về khoá học, xem giáo viên và học viên, cũng như quản lý các giáo viên và học viên khác. Mỗi khoá học có một giáo viên chính hoặc chủ sở hữu khoá học. Đây là giáo viên có thể quản lý các chế độ cài đặt như chuyển quyền sở hữu khoá học.

Học viên và giáo viên được xác định bằng mã nhận dạng duy nhất hoặc địa chỉ email của người dùng, do Directory API trả về. Người dùng hiện tại cũng có thể tham chiếu đến mã nhận dạng của riêng họ bằng cách sử dụng ký hiệu viết tắt "me".

Quyền quản lý trực tiếp bằng API Lớp học

Quản trị viên, học viên và giáo viên có các quyền khác nhau khi trực tiếp thêm hoặc xoá người dùng khỏi khoá học bằng API Lớp học.

Quản trị viên

Quản trị viên miền được phép bỏ qua quy trình mời và trực tiếp thêm học viên và giáo viên vào khoá học nếu đáp ứng các điều kiện sau:

  • Người dùng mà bạn đang thêm thuộc miền của quản trị viên.
  • Giáo viên chính của khoá học hoặc chủ sở hữu khoá học thuộc miền của quản trị viên.

Đối với người dùng hoặc khoá học nằm ngoài miền của quản trị viên, ứng dụng phải nhận được sự đồng ý của người dùng bằng cách gửi lời mời bằng phương thức invitations.create().

Sinh viên

Học viên có thể tự thêm mình vào một khoá học bằng cách gọi students.create() và chỉ định enrollmentCode của khoá học. enrollmentCode là giá trị nhận dạng duy nhất của khoá học có trong tài nguyên Course. Trong ứng dụng web của Lớp học, enrollmentCode có trong thẻ luồng và trang chi tiết về khoá học.

Giáo viên

Giáo viên không thể trực tiếp thêm người dùng vào khoá học và phải sử dụng phương thức invitations.create() để mời học viên và giáo viên khác tham gia khoá học.

Bảng sau đây mô tả người dùng nào được phép gửi yêu cầu đến các phương thức createdelete cho tài nguyên TeacherStudent.

Quản trị viên Giáo viên Sinh viên
CreateTeacher ✔️ ✖️ ✖️
DeleteTeacher ✔️ ✔️ ✖️
CreateStudent ✔️ ✖️ ✔️ 1
DeleteStudent ✔️ ✔️ ✔️ 2

1 Học viên chỉ có thể tự thêm mình vào khoá học.

2 Học viên chỉ có thể tự xoá mình khỏi một khoá học.

Quản lý giáo viên

Quản trị viên miền có thể trực tiếp thêm giáo viên trong miền của họ vào các khoá học bằng teachers.create(), như trong mẫu sau:

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;
         }


    }

}
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;
  }
}
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;
}
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)

Người cùng dạy có thể xoá các giáo viên khác khỏi khoá học bằng phương thức teachers.delete(). Thao tác này chỉ xoá giáo viên đã chỉ định khỏi khoá học và không ảnh hưởng đến việc chỉ định giáo viên đó cho các khoá học khác hoặc hồ sơ người dùng của họ.

Quản lý chủ sở hữu khoá học

Quản trị viên miền có thể chuyển quyền sở hữu khoá học giữa các giáo viên. Hãy xem phần Cập nhật chủ sở hữu khoá học để biết thông tin chi tiết quan trọng.

Quản lý học viên

Quản trị viên miền có thể trực tiếp thêm học viên trong miền của họ bằng phương thức students.create(). Nếu học viên tự thêm mình vào một khoá học, thì bạn phải có enrollmentCode.

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;
        }
    }

}
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;
  }
}
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;
}
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)

Việc xoá học viên khỏi một khoá học bằng phương thức students.delete() chỉ xoá học viên khỏi khoá học đã chỉ định và không ảnh hưởng đến việc đăng ký khoá học khác hoặc hồ sơ người dùng của học viên.

Truy xuất khoá học của người dùng

Để truy xuất danh sách các khoá học cho học viên hoặc giáo viên, hãy gọi courses.list() và cung cấp studentId hoặc teacherId của người dùng tương ứng.

Truy xuất hồ sơ của người dùng

Để truy xuất hồ sơ của một người dùng, bao gồm cả mã nhận dạng và tên, hãy gọi userProfiles.get() bằng mã nhận dạng, email hoặc "tôi" của người dùng yêu cầu. Để truy xuất trường emailAddress, bạn phải đưa phạm vi classroom.profile.emails vào.

id được trả về tương ứng với tài nguyên Người dùng API thư mục chứa studentId hoặc teacherId khớp.