Vos utilisateurs utilisent-ils Classroom avec Google Meet ? Consultez le guide de démarrage rapide d'Apps Script pour savoir comment vérifier la participation des élèves aux cours Google Meet.

Gérer les enseignants et les élèves

Les étudiants et les enseignants sont des mappages spécifiques entre un profil utilisateur et un cours, et représentent le rôle de cet utilisateur dans le cours. La désignation des élèves et des enseignants n'est pas globale. Un utilisateur peut être désigné comme enseignant pour un cours et pour un élève dans un autre. La désignation "élève" ou "enseignant" représente un ensemble d'autorisations pour un utilisateur spécifique dans un cours particulier.

Participants
Une ressource "Student" représente un utilisateur inscrit en tant qu'étudiant à un cours spécifique. Les étudiants sont autorisés à afficher les détails du cours et les enseignants de ce cours.
Enseignants
Une ressource "Enseignant" représente un utilisateur qui donne un cours spécifique. Les enseignants peuvent afficher et modifier les détails du cours, afficher les enseignants et les élèves, et gérer d'autres enseignants et élèves.

Les élèves et les enseignants sont identifiés par l'ID ou l'adresse e-mail unique de l'utilisateur, tel que renvoyé par l'API Directory. L'utilisateur actuel peut également faire référence à son propre ID à l'aide du raccourci "me".

Ajout direct

Les administrateurs de domaine sont autorisés à contourner le flux d'invitation et à ajouter directement les utilisateurs de leur domaine en tant qu'enseignants ou élèves aux cours de leur domaine. Un cours est considéré comme faisant partie du domaine de l'administrateur si son propriétaire appartient au domaine de l'administrateur. Pour les utilisateurs ou les cours n'appartenant pas au domaine d'un administrateur de domaine authentifié, les applications doivent obtenir le consentement de l'utilisateur en envoyant une invitation à l'aide de la méthode invitations.create().

Ajouter ou supprimer des enseignants

Les administrateurs de domaine peuvent ajouter directement des enseignants de leur domaine aux cours avec teachers.create(), comme illustré dans l'exemple suivant:

.NET

Classroom/extraits/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.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
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 java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;

/* Class to demonstrate the use of Classroom Add Teacher API */
public class AddTeacher {

  /* Scopes required by this API call. If modifying these scopes, delete your previously saved
  tokens/ folder. */
  static ArrayList<String> SCOPES =
      new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_ROSTERS));

  /**
   * 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.
   * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created.
   */
  public static Teacher addTeacher(String courseId, String teacherEmail)
      throws GeneralSecurityException, IOException {

    // Create the classroom API client.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    Classroom service =
        new Classroom.Builder(
                HTTP_TRANSPORT,
                GsonFactory.getDefaultInstance(),
                ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES))
            .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/extraits/src/ClassroomAddTeacher.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/extraits/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)

Si vous ajoutez des enseignants supplémentaires pour le compte d'un enseignant authentifié, vous devez utiliser la méthode invitations.create().

Vous pouvez supprimer des enseignants d'un cours avec la méthode teachers.delete(). Cela ne supprime que l'enseignant spécifié du cours et n'affecte pas son attribution aux autres cours ni son profil utilisateur.

Enregistrer ou supprimer des élèves

Les administrateurs de domaine peuvent ajouter directement des élèves au sein de leur domaine à l'aide de la méthode students.create(), comme illustré dans l'exemple suivant:

.NET

Classroom/extraits/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.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
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 java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;

/* Class to demonstrate the use of Classroom Add Student API */
public class AddStudent {

  /* Scopes required by this API call. If modifying these scopes, delete your previously saved
  tokens/ folder. */
  static ArrayList<String> SCOPES =
      new ArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_ROSTERS));

  /**
   * 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.
   * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created.
   */
  public static Student addStudent(String courseId, String enrollmentCode, String studentId)
      throws GeneralSecurityException, IOException {

    // Create the classroom API client.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    Classroom service =
        new Classroom.Builder(
                HTTP_TRANSPORT,
                GsonFactory.getDefaultInstance(),
                ClassroomCredentials.getCredentials(HTTP_TRANSPORT, SCOPES))
            .setApplicationName("Classroom samples")
            .build();

    Student student = new Student().setUserId(studentId);
    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/extraits/src/ClassroomAddStudent.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/extraits/classroom_add_student.py
from __future__ import print_function

import os

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

SCOPES = ['https://www.googleapis.com/auth/classroom.coursework.students']


def classroom_add_student_new(course_id):
    """
    Adds a student to a course, the teacher has access to.
    The file token.json stores the user's access and refresh tokens, and is
    created automatically when the authorization flow completes for the first
    time.
    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 = None
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w', encoding="utf8") as token:
            token.write(creds.to_json())

    enrollment_code = 'abc-def'
    student = {
            'userId': 'gduser1@workspacesamples.dev'
        }
    try:
        service = build('classroom', 'v1', credentials=creds)
        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))
        return student
    except HttpError as error:
        print(error)
        return error


if __name__ == '__main__':
    # Put the course_id of course for which student needs to be added.
    classroom_add_student_new(478800920837)

Si vous ajoutez des élèves au nom d'un enseignant authentifié, vous devez utiliser la méthode invitations.create().

Vous pouvez supprimer un élève d'un cours avec la méthode students.delete(). Cette action supprime uniquement l'étudiant spécifié du cours et n'a aucune incidence sur son inscription aux autres cours, ni sur son profil utilisateur.

Récupérer les cours d'un utilisateur

Pour récupérer la liste des cours d'un élève ou d'un enseignant, appelez courses.list() et fournissez le studentId ou le teacherId de l'utilisateur correspondant.

Récupérer le profil d'un utilisateur

Pour récupérer le profil abrégé d'un utilisateur, y compris son ID et son nom, appelez userProfiles.get() avec l'ID, l'adresse e-mail ou le "moi" de l'utilisateur à l'origine de la demande.

Pour récupérer le champ emailAddress, vous devez inclure le champ d'application classroom.profile.emails.

L'ID renvoyé correspond à la ressource Utilisateurs de l'API Directory, qui contient les valeurs studentId ou teacherId correspondantes.

Gérer les propriétaires de cours

Les administrateurs de domaine peuvent transférer la propriété des cours entre les enseignants. Pour en savoir plus, consultez la section Transférer la propriété d'un cours.