Google Classroom add-ons are now generally available to developers! Please see the add-ons documentation for more information.

Manage Courses

A Course resource represents a class, such as "MATH 127". It includes fields such as name, ownerId, and courseState. The Course resource is the parent resource of many other Classroom API resources.

Create a course

You can create a course using the courses.create() method. When you create a course, some fields such as the name and ownerId are required. You can optionally add metadata such as the description, section, or room.

Each course is assigned a unique ID by Classroom. Courses may also be referenced using an alias. See the manage aliases guide for information on adding project-scoped and domain-scoped aliases to courses.

The following pointers are helpful to keep in mind when creating courses using the Classroom API:

  • Create an alias by setting the course id field:

    • It's recommended that you add an alias to the course. When creating a Course, you can specify the alias within the id field. This automatically creates an alias for the course. You can also add an alias for a course using the courses.aliases.create() method.
    • Keep in mind that when reading course data using the courses.get() or courses.list() method, the id field returns the Classroom-assigned ID. You can retrieve a list of aliases for a course by making a request to the courses.aliases.list() method.
  • Only domain administrators can create courses on behalf of other users in their domain: Any other user receives a 403 error if specifying a user other than themselves in the ownerId field.

  • If the courseState field isn't specified, it is set to PROVISIONED by default: If the course is in the PROVISIONED state, the teacher identified in the ownerId field must accept the class in the Classroom UI or the course must be updated through the API to change the courseState to ACTIVE. ACTIVE courses are available to students.

  • Consumer accounts (*@gmail.com) cannot create courses in the ACTIVE state: Requests to do so return a 403: PERMISSION_DENIED error.

The following sample makes a request to the courses.create() method:

.NET

classroom/snippets/ClassroomSnippets/CreateCourse.cs
usingGoogle;
usingGoogle.Apis.Auth.OAuth2;
usingGoogle.Apis.Classroom.v1;
usingGoogle.Apis.Classroom.v1.Data;
usingGoogle.Apis.Services;
usingSystem;
namespaceClassroomSnippets
{
// Class to demonstrate the use of Classroom Create Course API
publicclassCreateCourse
{
/// <summary>
/// Creates a new course with description.
/// </summary>
/// <returns>newly created course</returns>
publicstaticCourseClassroomCreateCourse()
{
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. */
GoogleCredentialcredential=GoogleCredential.GetApplicationDefault()
.CreateScoped(ClassroomService.Scope.ClassroomCourses);
// Create Classroom API service.
varservice=newClassroomService(newBaseClientService.Initializer
{
HttpClientInitializer=credential,
ApplicationName="Classroom API Snippets"
});
// Create a new course with description.
varcourse=newCourse
{
Name="10th Grade Biology",
Section="Period 2",
DescriptionHeading="Welcome to 10th Grade Biology",
Description="We'll be learning about about the structure of living creatures "
+"from a combination of textbooks, guest lectures, and lab work. Expect "
+"to be excited!",
Room="301",
OwnerId="me",
CourseState="PROVISIONED"
};
course=service.Courses.Create(course).Execute();
// Prints the new created course Id and name.
Console.WriteLine("Course created: {0} ({1})",course.Name,course.Id);
returncourse;
}
catch(Exceptione)
{
// TODO(developer) - handle error appropriately
if(eisAggregateException)
{
Console.WriteLine("Credential Not found");
}
elseif(eisGoogleApiException)
{
Console.WriteLine("OwnerId not specified.");
}
else
{
throw;
}
}
returnnull;
}
}
}

Apps Script

classroom/snippets/createCourse.gs
/**
 * Creates 10th Grade Biology Course.
 * @see https://developers.google.com/classroom/reference/rest/v1/courses/create
 * return {string} Id of created course
 */
functioncreateCourse(){
letcourse={
name:'10th Grade Biology',
section:'Period 2',
descriptionHeading:'Welcome to 10th Grade Biology',
description:'We\'ll be learning about the structure of living creatures from a combination '+
'of textbooks, guest lectures, and lab work. Expect to be excited!',
room:'301',
ownerId:'me',
courseState:'PROVISIONED'
};
try{
// Create the course using course details.
course=Classroom.Courses.create(course);
console.log('Course created: %s (%s)',course.name,course.id);
returncourse.id;
}catch(err){
// TODO (developer) - Handle Courses.create() exception
console.log('Failed to create course %s with an error %s',course.name,err.message);
}
}

Go

classroom/snippets/createCourse.go
c:=&classroom.Course{
Name:"10th Grade Biology",
Section:"Period 2",
DescriptionHeading:"Welcome to 10th Grade Biology",
Description:"We'll be learning about about the structure of living creatures from a combination of textbooks, guest lectures, and lab work. Expect to be excited!",
Room:"301",
OwnerId:"me",
CourseState:"PROVISIONED",
}
course,err:=srv.Courses.Create(c).Do()
iferr!=nil{
log.Fatalf("Course unable to be created %v",err)
}

Java

classroom/snippets/src/main/java/CreateCourse.java
importcom.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
importcom.google.api.client.googleapis.json.GoogleJsonError;
importcom.google.api.client.googleapis.json.GoogleJsonResponseException;
importcom.google.api.client.http.javanet.NetHttpTransport;
importcom.google.api.client.json.gson.GsonFactory;
importcom.google.api.services.classroom.Classroom;
importcom.google.api.services.classroom.ClassroomScopes;
importcom.google.api.services.classroom.model.Course;
importjava.io.IOException;
importjava.security.GeneralSecurityException;
importjava.util.ArrayList;
importjava.util.Arrays;
/* Class to demonstrate the use of Classroom Create Course API */
publicclass CreateCourse{
/* Scopes required by this API call. If modifying these scopes, delete your previously saved
 tokens/ folder. */
staticArrayList<String>SCOPES=
newArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSES));
/**
 * Creates a course
 *
 * @return newly created course
 * @throws IOException - if credentials file not found.
 * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created.
 */
publicstaticCoursecreateCourse()throwsGeneralSecurityException,IOException{
// Create the classroom API client.
finalNetHttpTransportHTTP_TRANSPORT=GoogleNetHttpTransport.newTrustedTransport();
Classroomservice=
newClassroom.Builder(
HTTP_TRANSPORT,
GsonFactory.getDefaultInstance(),
ClassroomCredentials.getCredentials(HTTP_TRANSPORT,SCOPES))
.setApplicationName("Classroom samples")
.build();
Coursecourse=null;
try{
// Adding a new course with description. Set CourseState to `ACTIVE`. Possible values of
// CourseState can be found here:
// https://developers.google.com/classroom/reference/rest/v1/courses#coursestate
course=
newCourse()
.setName("10th Grade Biology")
.setSection("Period 2")
.setDescriptionHeading("Welcome to 10th Grade Biology")
.setDescription(
"We'll be learning about about the structure of living creatures "
+"from a combination of textbooks, guest lectures, and lab work. Expect "
+"to be excited!")
.setRoom("301")
.setOwnerId("me")
.setCourseState("ACTIVE");
course=service.courses().create(course).execute();
// Prints the new created course Id and name
System.out.printf("Course created: %s (%s)\n",course.getName(),course.getId());
}catch(GoogleJsonResponseExceptione){
GoogleJsonErrorerror=e.getDetails();
if(error.getCode()==400){
System.err.println("Unable to create course, ownerId not specified.\n");
}else{
throwe;
}
}
returncourse;
}
}

PHP

classroom/snippets/src/ClassroomCreateCourse.php
<?php
use Google\Client;
use Google\Service\Classroom;
use Google\Service\Classroom\Course;
use Google\Service\Exception;
function createCourse()
{
 /* 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.courses");
 $service = new Classroom($client);
 try {
 $course = new Course([
 'name' => '10th Grade Biology',
 'section' => 'Period 2',
 'descriptionHeading' => 'Welcome to 10th Grade Biology',
 'description' => 'We\'ll be learning about about the structure of living ' .
 'creatures from a combination of textbooks, guest ' .
 'lectures, and lab work. Expect to be excited!',
 'room' => '301',
 'ownerId' => 'me',
 'courseState' => 'PROVISIONED'
 ]);
 $course = $service->courses->create($course);
 printf("Course created: %s (%s)\n", $course->name, $course->id);
 return $course;
 } catch (Exception $e) {
 echo 'Message: ' . $e->getMessage();
 }
}

Python

classroom/snippets/classroom_create_course.py
importgoogle.auth
fromgoogleapiclient.discoveryimport build
fromgoogleapiclient.errorsimport HttpError
defclassroom_create_course():
"""
 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
 try:
 service = build("classroom", "v1", credentials=creds)
 course = {
 "name": "10th Grade Mathematics Probability-2",
 "section": "Period 3",
 "descriptionHeading": "Welcome to 10th Grade Mathematics",
 "description": """We'll be learning about about the
 polynomials from a
 combination of textbooks and guest lectures.
 Expect to be excited!""",
 "room": "302",
 "ownerId": "me",
 "courseState": "PROVISIONED",
 }
 # pylint: disable=maybe-no-member
 course = service.courses().create(body=course).execute()
 print(f"Course created: {(course.get('name'),course.get('id'))}")
 return course
 except HttpError as error:
 print(f"An error occurred: {error}")
 return error
if __name__ == "__main__":
 classroom_create_course()

Retrieve course details

You can retrieve a single course's metadata with the courses.get() method, as shown in the following sample:

.NET

classroom/snippets/ClassroomSnippets/GetCourse.cs
usingGoogle;
usingGoogle.Apis.Auth.OAuth2;
usingGoogle.Apis.Classroom.v1;
usingGoogle.Apis.Classroom.v1.Data;
usingGoogle.Apis.Services;
usingSystem;
namespaceClassroomSnippets
{
// Class to demonstrate the use of Classroom Get Course API
publicclassGetCourse
{
/// <summary>
/// Retrieve a single course's metadata.
/// </summary>
/// <param name="courseId">Id of the course.</param>
/// <returns>a course, null otherwise.</returns>
publicstaticCourseClassroomGetCourse(stringcourseId)
{
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. */
GoogleCredentialcredential=GoogleCredential.GetApplicationDefault()
.CreateScoped(ClassroomService.Scope.ClassroomCourses);
// Create Classroom API service.
varservice=newClassroomService(newBaseClientService.Initializer
{
HttpClientInitializer=credential,
ApplicationName="Classroom Snippets"
});
// Get the course details using course id
Coursecourse=service.Courses.Get(courseId).Execute();
Console.WriteLine("Course '{0}' found.\n",course.Name);
returncourse;
}
catch(Exceptione)
{
// TODO(developer) - handle error appropriately
if(eisAggregateException)
{
Console.WriteLine("Credential Not found");
}
elseif(eisGoogleApiException)
{
Console.WriteLine("Course does not exist.");
}
else
{
throw;
}
}
returnnull;
}
}
}

Apps Script

classroom/snippets/getCourse.gs
/**
 * Retrieves course by id.
 * @param {string} courseId
 * @see https://developers.google.com/classroom/reference/rest/v1/courses/get
 */
functiongetCourse(courseId){
try{
// Get the course details using course id
constcourse=Classroom.Courses.get(courseId);
console.log('Course "%s" found. ',course.name);
}catch(err){
// TODO (developer) - Handle Courses.get() exception of Handle Classroom API
console.log('Failed to found course %s with error %s ',courseId,err.message);
}
}

Go

classroom/snippets/getCourse.go
ctx:=context.Background()
srv,err:=classroom.NewService(ctx,option.WithHTTPClient(client))
iferr!=nil{
log.Fatalf("Unable to create classroom Client %v",err)
}
id:="123456"
course,err:=srv.Courses.Get(id).Do()
iferr!=nil{
log.Fatalf("Course unable to be retrieved %v",err)
}

Java

classroom/snippets/src/main/java/GetCourse.java
importcom.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
importcom.google.api.client.googleapis.json.GoogleJsonError;
importcom.google.api.client.googleapis.json.GoogleJsonResponseException;
importcom.google.api.client.http.javanet.NetHttpTransport;
importcom.google.api.client.json.gson.GsonFactory;
importcom.google.api.services.classroom.Classroom;
importcom.google.api.services.classroom.ClassroomScopes;
importcom.google.api.services.classroom.model.Course;
importjava.io.IOException;
importjava.security.GeneralSecurityException;
importjava.util.ArrayList;
importjava.util.Arrays;
/* Class to demonstrate the use of Classroom Get Course API */
publicclass GetCourse{
/* Scopes required by this API call. If modifying these scopes, delete your previously saved
 tokens/ folder. */
staticArrayList<String>SCOPES=
newArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSES));
/**
 * Retrieve a single course's metadata.
 *
 * @param courseId - Id of the course to return.
 * @return a course
 * @throws IOException - if credentials file not found.
 * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created.
 */
publicstaticCoursegetCourse(StringcourseId)throwsGeneralSecurityException,IOException{
// Create the classroom API client.
finalNetHttpTransportHTTP_TRANSPORT=GoogleNetHttpTransport.newTrustedTransport();
Classroomservice=
newClassroom.Builder(
HTTP_TRANSPORT,
GsonFactory.getDefaultInstance(),
ClassroomCredentials.getCredentials(HTTP_TRANSPORT,SCOPES))
.setApplicationName("Classroom samples")
.build();
Coursecourse=null;
try{
course=service.courses().get(courseId).execute();
System.out.printf("Course '%s' found.\n",course.getName());
}catch(GoogleJsonResponseExceptione){
// TODO(developer) - handle error appropriately
GoogleJsonErrorerror=e.getDetails();
if(error.getCode()==404){
System.out.printf("Course with ID '%s' not found.\n",courseId);
}else{
throwe;
}
}
returncourse;
}
}

PHP

classroom/snippets/src/ClassroomGetCourse.php
<?php
use Google\Client;
use Google\Service\Classroom;
use Google\Service\Exception;
function getCourse($courseId)
{
 /* 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.courses");
 $service = new Classroom($client);
 try {
 $course = $service->courses->get($courseId);
 printf("Course '%s' found.\n", $course->name);
 return $course;
 } catch (Exception $e) {
 if ($e->getCode() == 404) {
 printf("Course with ID '%s' not found.\n", $courseId);
 } else {
 throw $e;
 }
 }
}

Python

classroom/snippets/classroom_get_course.py
importgoogle.auth
fromgoogleapiclient.discoveryimport build
fromgoogleapiclient.errorsimport HttpError
defclassroom_get_course(course_id):
"""
 Prints the name of the 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
 course = None
 try:
 service = build("classroom", "v1", credentials=creds)
 course = service.courses().get(id=course_id).execute()
 print(f"Course found : {course.get('name')}")
 except HttpError as error:
 print(f"An error occurred: {error}")
 print(f"Course not found: {course_id}")
 return error
 return course
if __name__ == "__main__":
 # Put the course_id of course whose information needs to be fetched.
 classroom_get_course("course_id")

For a list of courses, use the courses.list(), as shown in the following sample:

.NET

classroom/snippets/ClassroomSnippets/ListCourses.cs
usingGoogle.Apis.Auth.OAuth2;
usingGoogle.Apis.Classroom.v1;
usingGoogle.Apis.Classroom.v1.Data;
usingGoogle.Apis.Services;
usingSystem;
usingSystem.Collections.Generic;
namespaceClassroomSnippets
{
// Class to demonstrate the use of Classroom List Course API
publicclassListCourses
{
/// <summary>
/// Retrieves all courses with metadata.
/// </summary>
/// <returns>list of courses with its metadata, null otherwise.</returns>
publicstaticList<Course>ClassroomListCourses()
{
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. */
GoogleCredentialcredential=GoogleCredential.GetApplicationDefault()
.CreateScoped(ClassroomService.Scope.ClassroomCourses);
// Create Classroom API service.
varservice=newClassroomService(newBaseClientService.Initializer
{
HttpClientInitializer=credential,
ApplicationName="Classroom Snippets"
});
stringpageToken=null;
varcourses=newList<Course>();
do
{
varrequest=service.Courses.List();
request.PageSize=100;
request.PageToken=pageToken;
varresponse=request.Execute();
courses.AddRange(response.Courses);
pageToken=response.NextPageToken;
}while(pageToken!=null);
Console.WriteLine("Courses:");
foreach(varcourseincourses)
{
// Print the courses available in classroom
Console.WriteLine("{0} ({1})",course.Name,course.Id);
}
returncourses;
}
catch(Exceptione)
{
// TODO(developer) - handle error appropriately
if(eisAggregateException)
{
Console.WriteLine("Credential Not found");
}
elseif(eisArgumentNullException)
{
Console.WriteLine("No courses found.");
}
else
{
throw;
}
}
returnnull;
}
}
}

Apps Script

classroom/snippets/listCourses.gs
/**
 * Lists all course names and ids.
 * @see https://developers.google.com/classroom/reference/rest/v1/courses/list
 */
functionlistCourses(){
letcourses=[];
constpageToken=null;
constoptionalArgs={
pageToken:pageToken,
pageSize:100
};
try{
constresponse=Classroom.Courses.list(optionalArgs);
courses=response.courses;
if(courses.length===0){
console.log('No courses found.');
return;
}
// Print the courses available in classroom
console.log('Courses:');
for(constcourseincourses){
console.log('%s (%s)',courses[course].name,courses[course].id);
}
}catch(err){
// TODO (developer) - Handle exception
console.log('Failed with error %s',err.message);
}
}

Java

classroom/snippets/src/main/java/ListCourses.java
importcom.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
importcom.google.api.client.http.javanet.NetHttpTransport;
importcom.google.api.client.json.gson.GsonFactory;
importcom.google.api.services.classroom.Classroom;
importcom.google.api.services.classroom.ClassroomScopes;
importcom.google.api.services.classroom.model.Course;
importcom.google.api.services.classroom.model.ListCoursesResponse;
importjava.io.IOException;
importjava.security.GeneralSecurityException;
importjava.util.ArrayList;
importjava.util.Arrays;
importjava.util.List;
/* Class to demonstrate the use of Classroom List Course API */
publicclass ListCourses{
/* Scopes required by this API call. If modifying these scopes, delete your previously saved
 tokens/ folder. */
staticArrayList<String>SCOPES=
newArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSES));
/**
 * Retrieves all courses with metadata
 *
 * @return list of courses with its metadata
 * @throws IOException - if credentials file not found.
 * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created.
 */
publicstaticList<Course>listCourses()throwsGeneralSecurityException,IOException{
// Create the classroom API client.
finalNetHttpTransportHTTP_TRANSPORT=GoogleNetHttpTransport.newTrustedTransport();
Classroomservice=
newClassroom.Builder(
HTTP_TRANSPORT,
GsonFactory.getDefaultInstance(),
ClassroomCredentials.getCredentials(HTTP_TRANSPORT,SCOPES))
.setApplicationName("Classroom samples")
.build();
StringpageToken=null;
List<Course>courses=newArrayList<>();
try{
do{
ListCoursesResponseresponse=
service.courses().list().setPageSize(100).setPageToken(pageToken).execute();
courses.addAll(response.getCourses());
pageToken=response.getNextPageToken();
}while(pageToken!=null);
if(courses.isEmpty()){
System.out.println("No courses found.");
}else{
System.out.println("Courses:");
for(Coursecourse:courses){
System.out.printf("%s (%s)\n",course.getName(),course.getId());
}
}
}catch(NullPointerExceptionne){
// TODO(developer) - handle error appropriately
System.err.println("No courses found.\n");
}
returncourses;
}
}

PHP

classroom/snippets/src/ClassroomListCourses.php
<?php
use Google\Service\Classroom;
use Google\Client;
function listCourses(): array
{
 /* 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.courses");
 $service = new Classroom($client);
 $courses = [];
 $pageToken = '';
 do {
 $params = [
 'pageSize' => 100,
 'pageToken' => $pageToken
 ];
 $response = $service->courses->listCourses($params);
 $courses = array_merge($courses, $response->courses);
 $pageToken = $response->nextPageToken;
 } while (!empty($pageToken));
 if (count($courses) == 0) {
 print "No courses found.\n";
 } else {
 print "Courses:\n";
 foreach ($courses as $course) {
 printf("%s (%s)\n", $course->name, $course->id);
 }
 }
 return $courses;
}

Python

classroom/snippets/classroom_list_courses.py
importgoogle.auth
fromgoogleapiclient.discoveryimport build
fromgoogleapiclient.errorsimport HttpError
defclassroom_list_courses():
"""
 Prints the list of 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()
 try:
 service = build("classroom", "v1", credentials=creds)
 courses = []
 page_token = None
 while True:
 # pylint: disable=maybe-no-member
 response = (
 service.courses().list(pageToken=page_token, pageSize=100).execute()
 )
 courses.extend(response.get("courses", []))
 page_token = response.get("nextPageToken", None)
 if not page_token:
 break
 if not courses:
 print("No courses found.")
 return
 print("Courses:")
 for course in courses:
 print(f"{course.get('name'),course.get('id')}")
 return courses
 except HttpError as error:
 print(f"An error occurred: {error}")
 return error
if __name__ == "__main__":
 print("Courses available are-------")
 classroom_list_courses()

You can also list courses filtered for a specific teacher or student. For more information, see Retrieve courses for a user.

Update course information

The Classroom API lets you update some course metadata after the course is created. Updating course information can be important when managing deleted users in a domain. For example, if a domain administrator must delete a teacher's account in the Google Admin console, they should transfer ownership of the course before doing so. This minimizes the risk of losing access to the course.

The following fields can be updated any time after the course is created:

  • name
  • section
  • descriptionHeading
  • description
  • room
  • courseState
  • ownerId

To update all fields in a course, use the courses.update() method, as shown in the following sample:

.NET

classroom/snippets/ClassroomSnippets/UpdateCourse.cs
usingGoogle.Apis.Auth.OAuth2;
usingGoogle.Apis.Classroom.v1;
usingGoogle.Apis.Classroom.v1.Data;
usingGoogle.Apis.Services;
usingSystem;
usingSystem.Net;
usingGoogle;
namespaceClassroomSnippets
{
// Class to demonstrate the use of Classroom Update Course API
publicclassUpdateCourse
{
/// <summary>
/// Update one field of course 
/// </summary>
/// <param name="courseId"></param>
/// <returns></returns>
/// <exception cref="GoogleApiException"></exception>
publicstaticCourseClassroomUpdateCourse(stringcourseId)
{
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. */
GoogleCredentialcredential=GoogleCredential.GetApplicationDefault()
.CreateScoped(ClassroomService.Scope.ClassroomCourses);
// Create Classroom API service.
varservice=newClassroomService(newBaseClientService.Initializer
{
HttpClientInitializer=credential,
ApplicationName="Classroom API Snippet"
});
Coursecourse=service.Courses.Get(courseId).Execute();
course.Section="Period 3";
course.Room="302";
course=service.Courses.Update(course,courseId).Execute();
Console.WriteLine("Course '{0}' updated.\n",course.Name);
returncourse;
}
catch(Exceptione)
{
// TODO(developer) - handle error appropriately
if(eisAggregateException)
{
Console.WriteLine("Credential Not found");
}
elseif(eisGoogleApiException)
{
Console.WriteLine("Failed to update the course. Error message: {0}",e.Message);
}
else
{
throw;
}
}
returnnull;
}
}
}

Apps Script

classroom/snippets/courseUpdate.gs
/**
 * Updates the section and room of Google Classroom.
 * @param {string} courseId
 * @see https://developers.google.com/classroom/reference/rest/v1/courses/update
 */
functioncourseUpdate(courseId){
try{
// Get the course using course ID
letcourse=Classroom.Courses.get(courseId);
course.section='Period 3';
course.room='302';
// Update the course
course=Classroom.Courses.update(course,courseId);
console.log('Course "%s" updated.',course.name);
}catch(e){
// TODO (developer) - Handle exception
console.log('Failed to update the course with error %s',e.message);
}
}

Java

classroom/snippets/src/main/java/UpdateCourse.java
importcom.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
importcom.google.api.client.googleapis.json.GoogleJsonError;
importcom.google.api.client.googleapis.json.GoogleJsonResponseException;
importcom.google.api.client.http.javanet.NetHttpTransport;
importcom.google.api.client.json.gson.GsonFactory;
importcom.google.api.services.classroom.Classroom;
importcom.google.api.services.classroom.ClassroomScopes;
importcom.google.api.services.classroom.model.Course;
importjava.io.IOException;
importjava.security.GeneralSecurityException;
importjava.util.ArrayList;
importjava.util.Arrays;
/* Class to demonstrate the use of Classroom Update Course API */
publicclass UpdateCourse{
/* Scopes required by this API call. If modifying these scopes, delete your previously saved
 tokens/ folder. */
staticArrayList<String>SCOPES=
newArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSES));
/**
 * Updates a course's metadata.
 *
 * @param courseId - Id of the course to update.
 * @return updated course
 * @throws IOException - if credentials file not found.
 * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created.
 */
publicstaticCourseupdateCourse(StringcourseId)throwsGeneralSecurityException,IOException{
// Create the classroom API client.
finalNetHttpTransportHTTP_TRANSPORT=GoogleNetHttpTransport.newTrustedTransport();
Classroomservice=
newClassroom.Builder(
HTTP_TRANSPORT,
GsonFactory.getDefaultInstance(),
ClassroomCredentials.getCredentials(HTTP_TRANSPORT,SCOPES))
.setApplicationName("Classroom samples")
.build();
Coursecourse=null;
try{
// Updating the section and room in a course
course=service.courses().get(courseId).execute();
course.setSection("Period 3");
course.setRoom("302");
course=service.courses().update(courseId,course).execute();
// Prints the updated course
System.out.printf("Course '%s' updated.\n",course.getName());
}catch(GoogleJsonResponseExceptione){
// TODO(developer) - handle error appropriately
GoogleJsonErrorerror=e.getDetails();
if(error.getCode()==404){
System.err.println("Course does not exist.\n");
}else{
throwe;
}
}
returncourse;
}
}

PHP

classroom/snippets/src/ClassroomUpdateCourse.php
<?php
use Google\Client;
use Google\Service\Classroom;
function updateCourse($courseId)
{
 /* 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.courses");
 $service = new Classroom($client);
 $course = $service->courses->get($courseId);
 $course->section = 'Period 3';
 $course->room = '302';
 $course = $service->courses->update($courseId, $course);
 printf("Course '%s' updated.\n", $course->name);
 return $course;
}

Python

classroom/snippets/classroom_update_course.py
importgoogle.auth
fromgoogleapiclient.discoveryimport build
fromgoogleapiclient.errorsimport HttpError
defclassroom_update_course(course_id):
"""
 Updates the courses names 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.
 """
 # pylint: disable=maybe-no-member
 creds, _ = google.auth.default()
 try:
 service = build("classroom", "v1", credentials=creds)
 # Updates the section and room of Google Classroom.
 course = service.courses().get(id=course_id).execute()
 course["name"] = "10th Grade Physics - Light"
 course["section"] = "Period 4"
 course["room"] = "410"
 course = service.courses().update(id=course_id, body=course).execute()
 print(f" Updated Course is: {course.get('name')}")
 return course
 except HttpError as error:
 print(f"An error occurred: {error}")
 return error
if __name__ == "__main__":
 # Put the course_id of course whose course needs to be updated.
 classroom_update_course("course_id")

You can also update specific fields using the courses.patch() method, as shown in the following sample:

.NET

classroom/snippets/ClassroomSnippets/PatchCourse.cs
usingGoogle.Apis.Auth.OAuth2;
usingGoogle.Apis.Classroom.v1;
usingGoogle.Apis.Classroom.v1.Data;
usingGoogle.Apis.Services;
usingSystem;
usingGoogle;
namespaceClassroomSnippets
{
// Class to demonstrate the use of Classroom Patch Course API
publicclassPatchUpdate
{
/// <summary>
/// Updates one or more fields in a course.
/// </summary>
/// <param name="courseId"></param>
/// <returns></returns>
/// <exception cref="GoogleApiException"></exception>
publicstaticCourseClassroomPatchUpdate(stringcourseId)
{
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. */
GoogleCredentialcredential=GoogleCredential.GetApplicationDefault()
.CreateScoped(ClassroomService.Scope.ClassroomCourses);
// Create Classroom API service.
varservice=newClassroomService(newBaseClientService.Initializer
{
HttpClientInitializer=credential,
ApplicationName="Classroom API Snippet"
});
varcourse=newCourse
{
Section="Period 3",
Room="302"
};
// Updates one or more fields of course.
varrequest=service.Courses.Patch(course,courseId);
request.UpdateMask="section,room";
course=request.Execute();
Console.WriteLine("Course '{0}' updated.\n",course.Name);
returncourse;
}
catch(Exceptione)
{
// TODO(developer) - handle error appropriately
if(eisAggregateException)
{
Console.WriteLine("Credential Not found");
}
elseif(eisGoogleApiException)
{
Console.WriteLine("Failed to update the course. Error message: {0}",e.Message);
}
else
{
throw;
}
}
returnnull;
}
}
}

Apps Script

classroom/snippets/patchCourse.gs
/**
 * Updates the section and room of Google Classroom.
 * @param {string} courseId
 * @see https://developers.google.com/classroom/reference/rest/v1/courses/patch
 */
functioncoursePatch(courseId){
letcourse={
'section':'Period 3',
'room':'302'
};
constmask={
updateMask:'section,room'
};
try{
// Update section and room in course.
course=Classroom.Courses.patch(body=course,id=courseId,updateMask=mask);
console.log('Course "%s" updated.',course.name);
}catch(err){
// TODO (developer) - Handle Courses.patch() exception
console.log('Failed to update the course. Error message: %s',err.message);
}
}

Java

classroom/snippets/src/main/java/PatchCourse.java
importcom.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
importcom.google.api.client.googleapis.json.GoogleJsonError;
importcom.google.api.client.googleapis.json.GoogleJsonResponseException;
importcom.google.api.client.http.javanet.NetHttpTransport;
importcom.google.api.client.json.gson.GsonFactory;
importcom.google.api.services.classroom.Classroom;
importcom.google.api.services.classroom.ClassroomScopes;
importcom.google.api.services.classroom.model.Course;
importjava.io.IOException;
importjava.security.GeneralSecurityException;
importjava.util.ArrayList;
importjava.util.Arrays;
/* Class to demonstrate the use of Classroom Patch Course API */
publicclass PatchCourse{
/* Scopes required by this API call. If modifying these scopes, delete your previously saved
 tokens/ folder. */
staticArrayList<String>SCOPES=
newArrayList<>(Arrays.asList(ClassroomScopes.CLASSROOM_COURSES));
/**
 * Updates one or more fields in a course.
 *
 * @param courseId - Id of the course to update.
 * @return updated course
 * @throws IOException - if credentials file not found.
 * @throws GeneralSecurityException - if a new instance of NetHttpTransport was not created.
 */
publicstaticCoursepatchCourse(StringcourseId)throwsGeneralSecurityException,IOException{
// Create the classroom API client.
finalNetHttpTransportHTTP_TRANSPORT=GoogleNetHttpTransport.newTrustedTransport();
Classroomservice=
newClassroom.Builder(
HTTP_TRANSPORT,
GsonFactory.getDefaultInstance(),
ClassroomCredentials.getCredentials(HTTP_TRANSPORT,SCOPES))
.setApplicationName("Classroom samples")
.build();
Coursecourse=null;
try{
course=newCourse().setSection("Period 3").setRoom("302");
course=service.courses().patch(courseId,course).setUpdateMask("section,room").execute();
System.out.printf("Course '%s' updated.\n",course.getName());
}catch(GoogleJsonResponseExceptione){
// TODO(developer) - handle error appropriately
GoogleJsonErrorerror=e.getDetails();
if(error.getCode()==404){
System.err.println("Course does not exist.\n");
}else{
throwe;
}
}
returncourse;
}
}

PHP

classroom/snippets/src/ClassroomPatchCourse.php
<?php
use Google\Service\Classroom;
use Google\Service\Classroom\Course;
use Google\Client;
function patchCourse($courseId)
{
 /* 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.courses");
 $service = new Classroom($client);
 try {
 $course = new Course([
 'section' => 'Period 3',
 'room' => '302'
 ]);
 $params = ['updateMask' => 'section,room'];
 $course = $service->courses->patch($courseId, $course, $params);
 printf("Course '%s' updated.\n", $course->name);
 return $course;
 } catch (Exception $e) {
 echo 'Message: ' . $e->getMessage();
 }
}

Python

classroom/snippets/classroom_patch_course.py
importgoogle.auth
fromgoogleapiclient.discoveryimport build
fromgoogleapiclient.errorsimport HttpError
defclassroom_patch_course(course_id):
"""
 Patch new course with existing course in the account 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.
 """
 # pylint: disable=maybe-no-member
 creds, _ = google.auth.default()
 try:
 service = build("classroom", "v1", credentials=creds)
 course = {"section": "Period 3", "room": "313"}
 course = (
 service.courses()
 .patch(id=course_id, updateMask="section,room", body=course)
 .execute()
 )
 print(f" Course updated are: {course.get('name')}")
 return course
 except HttpError as error:
 print(f"An error occurred: {error}")
if __name__ == "__main__":
 # Put the course_id of course with whom we need to patch some extra
 # information.
 classroom_patch_course("course_id")

Update the course owner

Domain administrators can use the courses.patch() method to update the ownerId field and transfer ownership of a course to a new teacher within their domain. If the new teacher is not already a co-teacher, make a request to the teachers.create() method to add them to the course before updating the ownerId field.

Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025年10月13日 UTC.