How to use Google Classroom APIs to retrieve and update classwork
We have been working with the Google Classroom APIs and would like to share a bit of our findings on how to use them.
Let’s assume your Google Cloud console is already set up and the Java quick start project as well. Any questions on how to do this, please follow along with our previous tutorial.
Once you’re all set let’s start retrieving the list of courses for a user.
https://developers.google.com/classroom/reference/rest/v1/courses/list
public static void main(String... args) throws IOException, GeneralSecurityException {
// Build a new authorized API client service.
final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
Classroom service = new Classroom.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
.setApplicationName(APPLICATION_NAME)
.build();
// List the first 10 courses that the user has access to.
ListCoursesResponse response = service.courses().list()
.setPageSize(10)
.execute();
List<Course> courses = response.getCourses();
if (courses == null || courses.size() == 0) {
System.out.println("No courses found.");
} else {
System.out.println("Courses:");
for (Course course : courses) {
System.out.printf("%s\n", course.getName());
}
}
It will respond with a list of courses and a pageToken for the next page so that when it’s not null we know there are more courses to be retrieved. This token would then be used on the request for the next page. It’s an optional parameter and when it’s not there, the api will return the first page with courses limited by the page size amount.
You can experiment with the api under the developers page.
Once we have a list of courses, we can create assignments for them, which we’ll call course work. This will be possible only for active courses.
The below would be a snippet for this based on https://developers.google.com/classroom/reference/rest/v1/courses.courseWork/create:
for (Course course : courses) {
if (course.getCourseState().equals("ACTIVE")) {
System.out.printf("%s\n", course.getName());
TimeOfDay timeOfDay = new TimeOfDay();
timeOfDay.setHours(14).setMinutes(30).setSeconds(30).setNanos(10);
Date date = new Date();
date.setYear(2021).setMonth(11).setDay(23);
LocalDate localDate = LocalDate.now().plusDays(7);
java.util.Date scheduledDate = java.util.Date.from(localDate.atStartOfDay()
.atZone(ZoneId.systemDefault())
.toInstant());
String s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").format(scheduledDate);
String studentUser = "student@gmail.com";
IndividualStudentsOptions individualStudentsOptions = new IndividualStudentsOptions();
ArrayList<String> studentIdList = new ArrayList<>();
studentIdList.add(studentUser);
individualStudentsOptions.setStudentIds(studentIdList);
CourseWork courseWork = new CourseWork()
.setCourseId(course.getId())
.setTitle("My course work")
.setDescription("desc")
// .setScheduledTime(s)
.setMaxPoints(100.0)
.setDueDate(date)
.setDueTime(timeOfDay)
.setAssigneeMode("INDIVIDUAL_STUDENTS")
// .setAssigneeMode("ALL_STUDENTS")
.setIndividualStudentsOptions(individualStudentsOptions)
.setWorkType("ASSIGNMENT")
.setState("PUBLISHED");
courseWork = service.courses().courseWork().create(course.getId(), courseWork).execute();
System.out.println(courseWork);
Here we’re looping through the list of courses and creating assignments for the active ones. We could also be retrieving the course based on its id or any other unique identifier we may want to use for this task.
We need to set the date and time for when the assignment is due and for this we create the respective some date and time objects (not to confuse with the java.util.Date class, which is used for scheduling when the assignment will be available).
Speaking of which, scheduling a time is only possible for assignments that are in draft mode, which is the default option. If they are already published, this option would become redundante and the Classroom API logs an error.
We also have the option to create the assignment for the whole class setAssigneeMode(ALL_STUDENTS)
or for individual students .setAssigneeMode(“INDIVIDUAL_STUDENTS”)
, which in this case requires as to populate a IndividualStudentsOptions
object.
Once we have a courseWork object such as the one below , we can also do updates to the assignments that we created using the patch endpoint.
courseWork = service.courses().courseWork().create(course.getId(), courseWork).execute();
https://developers.google.com/classroom/reference/rest/v1/courses.courseWork/patch
courseWork
.setCourseId(course.getId())
.setTitle("Updated title")
.setDescription("Updated description");
courseWork = service.courses().courseWork().patch(course.getId(), courseWork.getId(), courseWork).setUpdateMask("title, description").execute();
We need to be attentive to the object updateMask where we provide the string representation for each field we want to update, in our case, title and description.
We can also loop through the list of courseWorks set to a course and retrieve one that we like.
ListCourseWorkResponse listCourseWorkResponse = service.courses().courseWork().list(course.getId()).execute();
CourseWork courseWork = listCourseWorkResponse.getCourseWork().get(0);