Ödevleri yönetme

Classroom uygulaması üç tür akış öğesini destekler: CourseWork, CourseWorkMaterials ve Announcements. Bu kılavuzda CourseWork nasıl yönetileceği açıklanmaktadır ancak tüm akış öğelerinin API'leri benzerdir. Yayın öğesi türleri ve aralarındaki farklar hakkında daha fazla bilgi edinmek için API kaynakları bölümüne bakın.

CourseWork kaynağı, belirli bir kurstaki öğrencilere atanmış bir çalışma öğesini temsil eder. Bu öğe, son tarih veya maksimum puan gibi ek materyalleri ve ayrıntıları içerir. CourseWork'nın dört alt türü vardır: ödevler, test ödevleri, kısa yanıtlı sorular ve çoktan seçmeli sorular. Classroom API bu alt türlerden üçünü destekler: ödevler, kısa yanıtlı sorular ve çoktan seçmeli sorular. Bu türler CourseWork.workType alanı ile gösterilir.

CourseWork kaynağına ek olarak, tamamlanan işleri StudentSubmission kaynağıyla da yönetebilirsiniz.

Sınıf çalışması oluşturma

CourseWork yalnızca kursun öğretmeni adına oluşturulabilir. Bir öğrenci veya kurstaki öğretmen olmayan bir alan yöneticisi adına CourseWork oluşturmaya çalışmak PERMISSION_DENIED hatasına neden olur. Classroom'daki farklı roller hakkında daha fazla bilgi edinmek için Kullanıcı türleri başlıklı makaleyi inceleyin.

courses.courseWork.create yöntemini kullanarak CourseWork oluştururken bağlantıları aşağıdaki örnek kodda gösterildiği gibi materials olarak ekleyebilirsiniz:

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)

title ve workType alanları zorunludur. Diğer tüm alanlar isteğe bağlıdır. state belirtilmemişse CourseWork taslak durumunda oluşturulur.

Bağlı materyalleri CourseWork'ye dahil etmek için belirtilen bir hedefle Kaynak bağlama'yı kullanın. url Classroom, title ve küçük resim URL'sini (thumbnailUrl) otomatik olarak getirir. Classroom API, Google Drive ve YouTube materyallerini de benzer şekilde DriveFile kaynağı veya YouTubeVideo kaynağı ile birlikte kullanılabilecek şekilde yerel olarak destekler.

Teslim tarihi belirtmek için dueDate ve dueTime alanlarını ilgili UTC saatine ayarlayın. Son tarih gelecekteki bir tarih olmalıdır.

CourseWork yanıtı, atamaya diğer API isteklerinde referans vermek için kullanılabilecek sunucu tarafından atanmış bir tanımlayıcı içerir.

Retrieve CourseWork

İlgili kursun öğrencileri ve öğretmenleri adına CourseWork alabilirsiniz. Ayrıca, kursun öğretmeni olmasalar bile alan adı yöneticileri adına CourseWork alabilirsiniz. Belirli bir CourseWork öğesini almak için courses.courseWork.get kullanın. Tümünü almak için CourseWork (isteğe bağlı olarak bazı ölçütlerle eşleşir) courses.courseWork.list kullanın.

Gerekli kapsam, istekte bulunan kullanıcının kurstaki rolüne bağlıdır. Kullanıcı öğrenciyse aşağıdaki kapsamları kullanın:

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

Kullanıcı bir öğretmen veya alan yöneticisiyse aşağıdaki kapsamları kullanın:

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

Bir CourseWork'yı alma izninin olması, materyallere veya materyal meta verilerine erişim izni olduğu anlamına gelmez. Bu durum, uygulamada bir yöneticinin kursun üyesi olmaması halinde ekli bir Drive dosyasının başlığını göremeyebileceği anlamına gelir.

Öğrenci yanıtlarını yönetme

StudentSubmission kaynağı, bir öğrencinin CourseWork için yaptığı çalışmayı temsil eder. Kaynak, çalışmayla ilgili meta veriler (ör. çalışma durumu ve not) içerir. Yeni bir CourseWork oluşturulduğunda her öğrenci için örtülü olarak bir StudentSubmission oluşturulur.

Aşağıdaki bölümlerde, öğrenci yanıtlarını yönetmek için kullanılan yaygın işlemler açıklanmaktadır.

Öğrenci yanıtlarını alma

Öğrenciler kendi gönderimlerini, öğretmenler derslerindeki tüm öğrencilerin gönderimlerini, alan yöneticileri ise alanlarındaki tüm öğrencilerin tüm gönderimlerini alabilir. Her StudentSubmission öğesine bir tanımlayıcı atanır. Tanımlayıcıyı biliyorsanız gönderimi almak için courses.courseWork.studentSubmissions.get kullanın.

Aşağıdaki örnekte gösterildiği gibi, bazı ölçütlere uyan tüm courses.courseWork.studentSubmissions.list kaynaklarını almak için StudentSubmission yöntemini kullanın:

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)

Aşağıdaki örnekte gösterildiği gibi StudentSubmission parametresini belirterek belirli bir öğrenciye ait StudentSubmission kaynaklarını alın:userId

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")

Öğrenciler, Student kaynağında belirtildiği gibi benzersiz kimlik veya e-posta adresiyle tanımlanır. Mevcut kullanıcı, "me" kısaltmasını kullanarak kendi kimliğine de başvurabilir.

Bir kurstaki tüm ödevler için öğrenci gönderimlerini de alabilirsiniz. Bunu yapmak için aşağıdaki örnekte gösterildiği gibi courseWorkId olarak "-" değişmezini kullanın:

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()

Gerekli kapsam, istekte bulunan kullanıcının kurstaki rolüne bağlıdır. Kullanıcı bir öğretmen veya alan yöneticisiyse aşağıdaki kapsamı kullanın:

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

Kullanıcı öğrenciyse aşağıdaki kapsamı kullanın:

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

StudentSubmission alma izni, ekler veya ek meta verilerine erişim izni olduğu anlamına gelmez. Bu durum, uygulamada bir yöneticinin kursun üyesi olmaması halinde ekli bir Drive dosyasının başlığını göremeyebileceği anlamına gelir.

Öğrenci yanıtına ek ekleme

Link, DriveFile veya YouTubeVideo kaynağı ekleyerek öğrenci gönderimine bağlantı ekleyebilirsiniz. Bu işlem, aşağıdaki örnekte gösterildiği gibi courses.courseWork.studentSubmissions.modifyAttachments ile yapılır:

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")

Link ek, hedef url tarafından tanımlanır. Classroom, title ve küçük resim (thumbnailUrl) öğesini otomatik olarak getirir. StudentSubmissions öğesine eklenebilecek materyaller hakkında bilgi edinmek için Material bölümüne bakın.

StudentSubmission yalnızca kurs öğretmeni veya sahibi olan öğrenci tarafından değiştirilebilir. Yalnızca StudentSubmission öğesinin CourseWorkType ASSIGNMENT ise Materials ekleyebilirsiniz.

Gerekli kapsam, istekte bulunan kullanıcının kurstaki rolüne bağlıdır. Kullanıcı bir öğretmense aşağıdaki kapsamı kullanın:

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

Kullanıcı öğrenciyse aşağıdaki kapsamı kullanın:

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