課題と成績の管理

Classroom の UI は、アサインメント、テスト付きの課題、記述式問題、多肢選択式問題、資料の 5 種類の授業に対応しています。現在、Classroom API では 3 つの種類(API では CourseWorkType)として、アサインメント、記述式問題、多肢選択式問題がサポートされています。

MaterialsCourseWorkType リソースへの添付のみがサポートされています(アサインメント、記述式問題、多肢選択式問題)。

この機能を利用するには、CourseWork リソースを使用します。これは、特定のコースの生徒に割り当てられた課題または問題を表します。これには、期限や最大スコアなどの追加資料や詳細が含まれます。

CourseWork リソースに加えて、StudentSubmission リソースを使用して、完了した課題を管理できます。以降のセクションでは、これらについて詳しく説明します。

課題を作成する

課題を作成できるのはコースの教師の代理のみで、生徒の代理としてコースの課題を作成しようとすると、403 PERMISSION_DENIED エラーが発生します。同様に、ドメイン管理者が担当していないコースの課題を作成することもできません。このような課題を API 経由で作成しようとすると、403 PERMISSION_DENIED エラーが発生します。

courses.courseWork.create メソッドを使用して割り当てを作成する場合、次のサンプルコードに示すように、リンクを materials として添付できます。

Java

classroom/snippets/src/main/java/CreateCourseWork.java
CourseWork courseWork = null;
try {
  // Create a link to add as a material on course work.
  Link articleLink =
      new Link()
          .setTitle("SR-71 Blackbird")
          .setUrl("https://www.lockheedmartin.com/en-us/news/features/history/blackbird.html");

  // Create a list of Materials to add to course work.
  List<Material> materials = Arrays.asList(new Material().setLink(articleLink));

  /* Create new CourseWork object with the material attached.
  Set workType to `ASSIGNMENT`. Possible values of workType can be found here:
  https://developers.google.com/classroom/reference/rest/v1/CourseWorkType
  Set state to `PUBLISHED`. Possible values of state can be found here:
  https://developers.google.com/classroom/reference/rest/v1/courses.courseWork#courseworkstate */
  CourseWork content =
      new CourseWork()
          .setTitle("Supersonic aviation")
          .setDescription(
              "Read about how the SR-71 Blackbird, the world’s fastest and "
                  + "highest-flying manned aircraft, was built.")
          .setMaterials(materials)
          .setWorkType("ASSIGNMENT")
          .setState("PUBLISHED");

  courseWork = service.courses().courseWork().create(courseId, content).execute();

  /* Prints the created courseWork. */
  System.out.printf("CourseWork created: %s\n", courseWork.getTitle());
} catch (GoogleJsonResponseException e) {
  // TODO (developer) - handle error appropriately
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 404) {
    System.out.printf("The courseId does not exist: %s.\n", courseId);
  } else {
    throw e;
  }
  throw e;
} catch (Exception e) {
  throw e;
}
return courseWork;

Python

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


def classroom_create_coursework(course_id):
  """
  Creates the coursework the user has access to.
  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

  try:
    service = build("classroom", "v1", credentials=creds)
    coursework = {
        "title": "Ant colonies",
        "description": """Read the article about ant colonies
                              and complete the quiz.""",
        "materials": [
            {"link": {"url": "http://example.com/ant-colonies"}},
            {"link": {"url": "http://example.com/ant-quiz"}},
        ],
        "workType": "ASSIGNMENT",
        "state": "PUBLISHED",
    }
    coursework = (
        service.courses()
        .courseWork()
        .create(courseId=course_id, body=coursework)
        .execute()
    )
    print(f"Assignment created with ID {coursework.get('id')}")
    return coursework

  except HttpError as error:
    print(f"An error occurred: {error}")
    return error


if __name__ == "__main__":
  # Put the course_id of course whose coursework needs to be created,
  # the user has access to.
  classroom_create_coursework(453686957652)

結果には、他の API リクエストで割り当てを参照する際に使用できる、サーバー割り当ての識別子が含まれます。

Classroom API で作成した課題に、リンク先の資料を含めるには、リンクリソースに対象 URL を指定します。Classroom では、タイトルとサムネイル画像が自動的に取得されます。 また、Classroom API は Google ドライブと YouTube の資料もネイティブにサポートしています。これらは、DriveFile リソースYouTubeVideo リソースに同様に含めることができます。

期限を指定するには、dueDate フィールドと dueTime フィールドを対応する UTC 時刻に設定します。期限には将来の日付を指定する必要があります。

課題と質問を取得する

対応するコースの生徒と教師、またはドメイン管理者が割り当てた課題と質問を取得できます。特定の課題または問題を取得するには、courses.courseWork.get を使用します。すべての課題または質問(必要に応じていくつかの条件に一致するもの)を取得するには、courses.courseWork.list を使用します。

必要なスコープは、リクエスト元のユーザーがコースで持っているロールによって異なります。ユーザーが生徒である場合は、次のいずれかのスコープを使用します。

  • https://www.googleapis.com/auth/classroom.coursework.me.readonly
  • https://www.googleapis.com/auth/classroom.coursework.me

ユーザーが教師またはドメイン管理者の場合は、次のいずれかのスコープを使用します。

  • https://www.googleapis.com/auth/classroom.coursework.students.readonly
  • https://www.googleapis.com/auth/classroom.coursework.students

課題または質問を取得する権限があるからといって、資料やマテリアル メタデータにアクセスする権限があることにはなりません。つまり、管理者がコースのメンバーでない場合は、添付されたドライブ ファイルのタイトルが表示されない可能性があります。管理者にユーザー ファイルへのアクセスを許可する場合は、ドメイン全体の委任ガイドをご覧ください。

生徒の回答を管理する

StudentSubmission リソースは、課題や問題に対する生徒の提出物と成績を表します。新しい質問または課題が作成されると、各生徒に対して StudentSubmission リソースが暗黙的に作成されます。

以下のセクションでは、生徒の回答を管理する一般的な操作について説明します。

生徒の解答を取得する

生徒は自分の提出物を取得でき、教師はコース内のすべての生徒の提出物を取得でき、ドメイン管理者はドメイン内のすべての生徒の提出物をすべて取得できます。各生徒の提出物には識別子が割り当てられます。識別子がわかっている場合は、courses.courseWork.studentSubmissions.get を使用して取得します。

次のサンプルに示すように、courses.courseWork.studentSubmissions.list メソッドを使用して、いくつかの条件に一致する StudentSubmission リソースを取得します。

Java

classroom/snippets/src/main/java/ListSubmissions.java
List<StudentSubmission> studentSubmissions = new ArrayList<>();
String pageToken = null;

try {
  do {
    ListStudentSubmissionsResponse response =
        service
            .courses()
            .courseWork()
            .studentSubmissions()
            .list(courseId, courseWorkId)
            .setPageToken(pageToken)
            .execute();

    /* Ensure that the response is not null before retrieving data from it to avoid errors. */
    if (response.getStudentSubmissions() != null) {
      studentSubmissions.addAll(response.getStudentSubmissions());
      pageToken = response.getNextPageToken();
    }
  } while (pageToken != null);

  if (studentSubmissions.isEmpty()) {
    System.out.println("No student submission found.");
  } else {
    for (StudentSubmission submission : studentSubmissions) {
      System.out.printf(
          "Student id (%s), student submission id (%s)\n",
          submission.getUserId(), submission.getId());
    }
  }
} catch (GoogleJsonResponseException e) {
  // TODO (developer) - handle error appropriately
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 404) {
    System.out.printf(
        "The courseId (%s) or courseWorkId (%s) does not exist.\n", courseId, courseWorkId);
  } else {
    throw e;
  }
} catch (Exception e) {
  throw e;
}
return studentSubmissions;

Python

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


def classroom_list_submissions(course_id, coursework_id):
  """
  Creates the courses the user has access to.
  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
  submissions = []
  page_token = None

  try:
    service = build("classroom", "v1", credentials=creds)
    while True:
      coursework = service.courses().courseWork()
      response = (
          coursework.studentSubmissions()
          .list(
              pageToken=page_token,
              courseId=course_id,
              courseWorkId=coursework_id,
              pageSize=10,
          )
          .execute()
      )
      submissions.extend(response.get("studentSubmissions", []))
      page_token = response.get("nextPageToken", None)
      if not page_token:
        break

    if not submissions:
      print("No student submissions found.")

    print("Student Submissions:")
    for submission in submissions:
      print(
          "Submitted at:"
          f"{(submission.get('id'), submission.get('creationTime'))}"
      )

  except HttpError as error:
    print(f"An error occurred: {error}")
    submissions = None
  return submissions


if __name__ == "__main__":
  # Put the course_id and coursework_id of course whose list needs to be
  # submitted.
  classroom_list_submissions(453686957652, 466086979658)

次のサンプルに示すように、userId パラメータを指定して、特定の生徒に属する StudentSubmission リソースを取得します。

Java

classroom/snippets/src/main/java/ListStudentSubmissions.java
List<StudentSubmission> studentSubmissions = new ArrayList<>();
String pageToken = null;

try {
  do {
    // Set the userId as a query parameter on the request.
    ListStudentSubmissionsResponse response =
        service
            .courses()
            .courseWork()
            .studentSubmissions()
            .list(courseId, courseWorkId)
            .setPageToken(pageToken)
            .set("userId", userId)
            .execute();

    /* Ensure that the response is not null before retrieving data from it to avoid errors. */
    if (response.getStudentSubmissions() != null) {
      studentSubmissions.addAll(response.getStudentSubmissions());
      pageToken = response.getNextPageToken();
    }
  } while (pageToken != null);

  if (studentSubmissions.isEmpty()) {
    System.out.println("No student submission found.");
  } else {
    for (StudentSubmission submission : studentSubmissions) {
      System.out.printf("Student submission: %s.\n", submission.getId());
    }
  }

Python

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


def classroom_list_student_submissions(course_id, coursework_id, user_id):
  """
  Creates the courses the user has access to.
  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
  submissions = []
  page_token = None

  try:
    service = build("classroom", "v1", credentials=creds)
    while True:
      coursework = service.courses().courseWork()
      response = (
          coursework.studentSubmissions()
          .list(
              pageToken=page_token,
              courseId=course_id,
              courseWorkId=coursework_id,
              userId=user_id,
          )
          .execute()
      )
      submissions.extend(response.get("studentSubmissions", []))
      page_token = response.get("nextPageToken", None)
      if not page_token:
        break

    if not submissions:
      print("No student submissions found.")

    print("Student Submissions:")
    for submission in submissions:
      print(
          "Submitted at:"
          f"{(submission.get('id'), submission.get('creationTime'))}"
      )

  except HttpError as error:
    print(f"An error occurred: {error}")
  return submissions


if __name__ == "__main__":
  # Put the course_id, coursework_id and user_id of course whose list needs
  # to be submitted.
  classroom_list_student_submissions(453686957652, 466086979658, "me")

学生は、Google Admin SDK から返されるユーザーの一意の ID またはメールアドレスによって識別されます。現在のユーザーは、短縮形 "me" を使用して自身の ID を参照することもできます。

コース内のすべての課題について、生徒の提出物を取得することもできます。そのためには、次のサンプルに示すように、リテラル "-"courseWorkId として使用します。

Java

service.courses().courseWork().studentSubmissions()
    .list(courseId, "-")
    .set("userId", userId)
    .execute();

Python

service.courses().courseWork().studentSubmissions().list(
    courseId=<course ID or alias>,
    courseWorkId='-',
    userId=<user ID>).execute()

必要なスコープは、リクエスト元のユーザーがコースで持っているロールによって異なります。ユーザーが教師またはドメイン管理者の場合は、次のスコープを使用します。

  • https://www.googleapis.com/auth/classroom.coursework.students.readonly
  • https://www.googleapis.com/auth/classroom.coursework.students

ユーザーが生徒の場合は、次のスコープを使用します。

  • https://www.googleapis.com/auth/classroom.coursework.me.readonly
  • https://www.googleapis.com/auth/classroom.coursework.me

生徒の提出物を取得する権限が付与されていても、添付ファイルまたは添付ファイルのメタデータにアクセスする権限があることを意味するものではありません。つまり、管理者がコースのメンバーでない場合、添付ファイルのタイトルは表示されないことがあります。管理者にユーザー ファイルへのアクセスを許可する場合は、ドメイン全体の委任ガイドをご覧ください。

生徒の回答に添付ファイルを追加する

生徒の提出物にリンクを添付するには、LinkDriveFile、または YouTubeVideo のリソースを添付します。これは、次のサンプルに示すように、courses.courseWork.studentSubmissions.modifyAttachments を使用して行います。

Java

classroom/snippets/src/main/java/ModifyAttachmentsStudentSubmission.java
StudentSubmission studentSubmission = null;
try {
  // Create ModifyAttachmentRequest object that includes a new attachment with a link.
  Link link = new Link().setUrl("https://en.wikipedia.org/wiki/Irrational_number");
  Attachment attachment = new Attachment().setLink(link);
  ModifyAttachmentsRequest modifyAttachmentsRequest =
      new ModifyAttachmentsRequest().setAddAttachments(Arrays.asList(attachment));

  // The modified studentSubmission object is returned with the new attachment added to it.
  studentSubmission =
      service
          .courses()
          .courseWork()
          .studentSubmissions()
          .modifyAttachments(courseId, courseWorkId, id, modifyAttachmentsRequest)
          .execute();

  /* Prints the modified student submission. */
  System.out.printf(
      "Modified student submission attachments: '%s'.\n",
      studentSubmission.getAssignmentSubmission().getAttachments());
} catch (GoogleJsonResponseException e) {
  // TODO (developer) - handle error appropriately
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 404) {
    System.out.printf(
        "The courseId (%s), courseWorkId (%s), or studentSubmissionId (%s) does "
            + "not exist.\n",
        courseId, courseWorkId, id);
  } else {
    throw e;
  }
} catch (Exception e) {
  throw e;
}
return studentSubmission;

Python

classroom/snippets/classroom_add_attachment.py
def classroom_add_attachment(course_id, coursework_id, submission_id):
  """
  Adds attachment to existing 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
  request = {
      "addAttachments": [
          {"link": {"url": "http://example.com/quiz-results"}},
          {"link": {"url": "http://example.com/quiz-reading"}},
      ]
  }

  try:
    service = build("classroom", "v1", credentials=creds)
    while True:
      coursework = service.courses().courseWork()
      coursework.studentSubmissions().modifyAttachments(
          courseId=course_id,
          courseWorkId=coursework_id,
          id=submission_id,
          body=request,
      ).execute()

  except HttpError as error:
    print(f"An error occurred: {error}")


if __name__ == "__main__":
  # Put the course_id, coursework_id and submission_id of course in which
  # attachment needs to be added.
  classroom_add_attachment("course_id", "coursework_id", "me")

リンクの添付ファイルはターゲット URL によって定義されます。Classroom はタイトルとサムネイル画像を自動的に取得します。その他の資料については、それぞれのリファレンス ページをご覧ください。

StudentSubmission を変更できるのは、コースの教師またはそれを所有する生徒のみです。Materials をアタッチできるのは、学生の提出物の CourseWorkTypeASSIGNMENT の場合のみです。

必要なスコープは、リクエスト元のユーザーがコースで持っているロールによって異なります。ユーザーが教師の場合は、次のスコープを使用します。

  • https://www.googleapis.com/auth/classroom.coursework.students

ユーザーが生徒の場合は、次のスコープを使用します。

  • https://www.googleapis.com/auth/classroom.coursework.me

生徒の回答状態を管理する

生徒の解答は、提出を取り消す、提出または返却することができます。StudentSubmission の状態フィールドは現在の状態を示します。状態を変更するには、次のいずれかのメソッドを呼び出します。

これらのメソッドはすべて空の本体を取ります。例:

Java

classroom/snippets/src/main/java/ReturnStudentSubmission.java
try {
  service
      .courses()
      .courseWork()
      .studentSubmissions()
      .classroomReturn(courseId, courseWorkId, id, null)
      .execute();
} catch (GoogleJsonResponseException e) {
  // TODO (developer) - handle error appropriately
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 404) {
    System.out.printf(
        "The courseId (%s), courseWorkId (%s), or studentSubmissionId (%s) does "
            + "not exist.\n",
        courseId, courseWorkId, id);
  } else {
    throw e;
  }
} catch (Exception e) {
  throw e;
}

Python

service.courses().courseWork().studentSubmission().turnIn(
    courseId=<course ID or alias>,
    courseWorkId=<courseWork ID>,
    id=<studentSubmission ID>,
    body={}).execute()

提出または再請求を行えるのは、StudentSubmission を所有している生徒のみです。 再請求できるのは提出済みの提出物のみです。コースの教師は、オン状態の StudentSubmission のみを返すことができます。

生徒の回答を採点する

StudentSubmission リソースには、成績を保存する 2 つのフィールドがあります。assignedGrade(生徒に報告される成績)と draftGrade(教師にのみ表示される仮成績)です。これらのフィールドは、次のサンプルに示すように、適切なフィールドを含むフィールド マスクで courses.courseWork.studentSubmissions.patch を使用して更新します。

Java

classroom/snippets/src/main/java/PatchStudentSubmission.java
StudentSubmission studentSubmission = null;
try {
  // Updating the draftGrade and assignedGrade fields for the specific student submission.
  StudentSubmission content =
      service
          .courses()
          .courseWork()
          .studentSubmissions()
          .get(courseId, courseWorkId, id)
          .execute();
  content.setAssignedGrade(90.00);
  content.setDraftGrade(80.00);

  // The updated studentSubmission object is returned with the new draftGrade and assignedGrade.
  studentSubmission =
      service
          .courses()
          .courseWork()
          .studentSubmissions()
          .patch(courseId, courseWorkId, id, content)
          .set("updateMask", "draftGrade,assignedGrade")
          .execute();

  /* Prints the updated student submission. */
  System.out.printf(
      "Updated student submission draft grade (%s) and assigned grade (%s).\n",
      studentSubmission.getDraftGrade(), studentSubmission.getAssignedGrade());
} catch (GoogleJsonResponseException e) {
  // TODO (developer) - handle error appropriately
  GoogleJsonError error = e.getDetails();
  if (error.getCode() == 404) {
    System.out.printf(
        "The courseId (%s), courseWorkId (%s), or studentSubmissionId (%s) does "
            + "not exist.\n",
        courseId, courseWorkId, id);
  } else {
    throw e;
  }
} catch (Exception e) {
  throw e;
}
return studentSubmission;

Python

studentSubmission = {
  'assignedGrade': 99,
  'draftGrade': 80
}
service.courses().courseWork().studentSubmissions().patch(
    courseId=<course ID or alias>,
    courseWorkId=<courseWork ID>,
    id=<studentSubmission ID>,
    updateMask='assignedGrade,draftGrade',
    body=studentSubmission).execute()

Classroom の UI を使用する場合、教師は仮成績を保存するまで成績を割り当てられません。その後、割り当てられた成績を生徒に返却できます。アプリケーションはこの動作をエミュレートする必要があります。アプリケーションは、次の 2 つの方法のいずれかで生徒の課題を採点できます。

  • draftGrade のみを割り当てます。これは、たとえば最終決定前に教師が手動で成績を審査する場合などに便利です。生徒は仮成績を表示できません。

  • 課題を完全に採点するには、draftGradeassignedGrade の両方を割り当てます。

割り当てられた成績を一覧表示する

特定のコースワーク アイテムのすべての成績を一覧表示するには、courses.courseWork.studentSubmissions.list メソッドのレスポンス オブジェクトを確認します。

Java

classroom/snippets/src/main/java/ListStudentSubmissions.java
  ListStudentSubmissionsResponse response =
      service
          .courses()
          .courseWork()
          .studentSubmissions()
          .list(courseId, courseWorkId)
          .setPageToken(pageToken)
          .execute();

  /* Ensure that the response is not null before retrieving data from it to avoid errors. */
  if (response.getStudentSubmissions() != null) {
    studentSubmissions.addAll(response.getStudentSubmissions());
    pageToken = response.getNextPageToken();
  }
} while (pageToken != null);

if (studentSubmissions.isEmpty()) {
  System.out.println("No student submissions found.");
} else {
  for (StudentSubmission submission : studentSubmissions) {
    System.out.printf(
        "User ID %s, Assigned grade: %s\n",
        submission.getUserId(), submission.getAssignedGrade());
  }
}

Python

response = coursework.studentSubmissions().list(
    courseId=course_id,
    courseWorkId=coursework_id,
    pageSize=10).execute()
submissions.extend(response.get('studentSubmissions', []))

if not submissions:
    print('No student submissions found.')

print('Student Submissions:')
for submission in submissions:
    print(f"Submitted at:"
          f"{(submission.get('userId'), submission.get('assignedGrade'))}")