Are your users using Classroom with Google Meet? Check out the Apps Script quickstart covering how to check student attendance in Google Meet courses.

Manage Teachers and Students

Students and teachers are specific mappings between a user profile and a course, representing that user's role in the course. Designations of student and teacher are not global: a user can be assigned as a teacher for one course and a student in another. The designation "student" or "teacher" represents a set of permissions for a particular user in a particular course.

Students
A Student resource represents a user who is enrolled as a student in a specific course. Students are permitted to view the course details and teachers for that course.
Teachers
A Teacher resource represents a user who teaches a specific course. Teachers are permitted to view and change the course details, view teachers and students, and manage additional teachers and students.

Students and teachers are identified by the unique ID or email address of the user, as returned by the Google Admin SDK. The current user may also refer to their own ID using the "me" shorthand.

Direct-adding

Domain administrators are permitted to bypass the invitation flow and directly add users within their domain as teachers or students to courses within their domain. A course is considered within the domain of the admin if the owner of the course is in the admin's domain. For users or courses outside the domain of an authenticated domain administrator, applications must obtain the user's consent by sending an invitation with the invitations.create() method.

Add or remove teachers

Domain administrators can directly add teachers within their domain to courses with teachers.create(), as shown in the following sample:

.NET

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


    }

}

Java

classroom/snippets/src/main/java/AddTeacher.java
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequestInitializer;
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 com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

/* Class to demonstrate the use of Classroom Add Teacher API */
public class AddTeacher {
    /**
     * 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.
     */
    public static Teacher addTeacher(String courseId, String teacherEmail)
            throws IOException {
        /* Load pre-authorized user credentials from the environment.
           TODO(developer) - See https://developers.google.com/identity for
            guides on implementing OAuth2 for your application. */
        GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
                .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_ROSTERS));
        HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
                credentials);

        // Create the classroom API client
        Classroom service = new Classroom.Builder(new NetHttpTransport(),
                GsonFactory.getDefaultInstance(),
                requestInitializer)
                .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;
    }
}

PHP

classroom/snippets/src/classroom_add_teacher.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;
}

Python

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)

If you are adding additional teachers on behalf of an authenticated teacher, you must use the invitations.create() method.

You can remove additional teachers from a course with the teachers.delete() method. This only removes the specified teacher from the course and does not affect their assignment to other courses or their user profile.

Enroll or remove students

Domain administrators can directly add students within their domain with the students.create() method, as shown in the following sample:

.NET

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

}

Java

classroom/snippets/src/main/java/AddStudent.java
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequestInitializer;
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 com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.Collections;

/* Class to demonstrate the use of Classroom Add Student API */
public class AddStudent {
    /**
     * 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.
     */
    public static Student addStudent(String courseId, String enrollmentCode)
            throws IOException {
        /* Load pre-authorized user credentials from the environment.
           TODO(developer) - See https://developers.google.com/identity for
            guides on implementing OAuth2 for your application. */
        GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
                .createScoped(Collections.singleton(ClassroomScopes.CLASSROOM_ROSTERS));
        HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
                credentials);

        // Create the classroom API client
        Classroom service = new Classroom.Builder(new NetHttpTransport(),
                GsonFactory.getDefaultInstance(),
                requestInitializer)
                .setApplicationName("Classroom samples")
                .build();

        Student student = new Student().setUserId("me");
        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;
    }
}

PHP

classroom/snippets/src/classroom_add_student.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;
}

Python

classroom/snippets/classroom_snippets.py
enrollment_code = 'abcdef'
student = {
    'userId': 'me'
}
try:
    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))
except errors.HttpError as error:
    print('You are already a member of this course.')

If you are adding students on behalf of an authenticated teacher, you must use the invitations.create() method.

You can remove a student from a course with the students.delete() method. This only removes the specified student from the course and does not affect their enrollment in other courses or their user profile.

Retrieve a user's courses

To retrieve a list of courses for a student or teacher, use the courses.list() and supply the corresponding user's studentId or teacherId.

Retrieve a user's profile

To retrieve the abridged profile, including ID and name, for a user, call userProfiles.get() with the user's ID, email, or "me" for the requesting user.

To retrieve the emailAddress field, you must include the classroom.profile.emails scope.

The ID returned corresponds to the Directory API Users resource containing the matching studentId or teacherId.