Why?
Most commonly, so that you can sync membership with a list on a Sheet, removing some students (e.g. any no longer on roll or who have been moved into a different group) and adding others (e.g. new to roll or moved into the group).
How?
Run the following function in the Apps Script Editor:
function getStudentsFromClassroom() {
const courseId = '012345678910'; // Replace this with the correct id
let students = [];
let nextPageToken = '';
do {
let response = Classroom.Courses.Students.list(courseId, { pageSize: 40, pageToken: nextPageToken });
nextPageToken = response.nextPageToken;
if (response && response.students) {
for (const student of response.students) {
students.push([student.profile.name.givenName,
student.profile.name.familyName,
student.profile.emailAddress.toLowerCase()]);
}
}
} while (nextPageToken);
students = students.sort((a, b) => a[2] > b[2] ? 1 : -1); // Sorts the emails alphabetically
SpreadsheetApp.getActiveSheet().getRange(1, 1, students.length, 3).setValues(students);
}Notes
To get the course id for the first line, see Find the IDs of your courses.
The above code returns the name and email addresses of the students enrolled in the course, but only the email address is actually required to modify course membership. The givenName and familyName pair can be replaced by a single fullName.
The final line (SpreadsheetApp…) writes the names and email addresses to the container Sheet, but it is more likely that you would want to replace this with return students; so that the calling function can process the students in the next part of the script.
Permissions
To run successfully, you might (try it first and if it runs, don’t worry!) need to add the following scope to the “appsscript.json” manifest file:
"oauthScopes": [
"https://www.googleapis.com/auth/classroom.rosters.readonly"
]
