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 Course Aliases

You can reference courses by an different name with a Course Alias resource. Course Aliases are a mapping between Google Classroom course identifiers and external course identifiers.

We recommend that anytime you create a course from an SIS or link a course to an SIS, that the SIS’s courseID is used as the course alias. The Classroom API lets you do this directly in course creation by specifying the id parameter of the course as the alias. If the alias already exists, course creation will fail with an ALREADY_EXISTS (409) error. This will prevent the creation of duplicate courses if there is a bug in the sync program.

Aliases come in two flavors: domain-wide and project-wide.

  • Domain-wide aliases use a prefix of d: and can be seen by anybody using the Classroom API.
  • Project-wide aliases use a prefix of p: and can only be seen and used by the application (developer console project) that created them.

Aliases can be used anywhere in the API that expects a course identifier. This means that once an alias is registered using the API, that alias can be used to read and modify courses and roster information.

From the SIS synchronization perspective, this means that the SIS internal identifier for a course can be registered as a domain-wide alias for the course. That way any developer who integrates with both the SIS and classroom can simply use the SIS identifier to interact with Classroom data.

For example, if we assume the SIS name is school and the internal identifier used by the SIS for a particular course is math_101, you could create an alias as d:school_math_101.

Add an alias for a new course

To add an alias for a new course, set course.id to the desired alias when making the courses.create request.

Apps Script

classroom/snippets/createAlias.gs
/**
 * Creates Course with an alias specified
 */
function createAlias() {
  let course = {
    id: 'p:bio_101',
    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);
    Logger.log('Course created: %s (%s)', course.name, course.id);
  } catch (err) {
    // TODO (developer) - Handle Courses.create() exception
    Logger.log('Failed to create course %s with an error %s', course.name, err.message);
  }
}

Python

classroom/snippets/classroom_add_alias_new.py
SCOPES = ['https://www.googleapis.com/auth/classroom.courses']


def classroom_add_alias_new():
    """
        Creates a course with alias specification the user 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.
    """
    # pylint: disable=maybe-no-member
    creds = None
    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())

    alias = 'd:school_physics_333'
    course = {
        'id': alias,
        'name': 'English',
        'section': 'Period 2',
        'description': 'Course Description',
        'room': '301',
        'ownerId': 'me'
    }
    try:
        print('-------------')
        service = build('classroom', 'v1', credentials=creds)
        course = service.courses().create(body=course).execute()
        print('====================================')

    except HttpError as error:
        print('An error occurred: %s' % error)
    return course


if __name__ == '__main__':
    # pylint: disable=too-many-arguments
    # Put the course_id of course whose alias needs to be created.
    classroom_add_alias_new()

Add an alias for an existing course

To add the alias on an existing course, you can set alias to the desired alias name and use the courses.alias.create method.

Apps Script

classroom/snippets/addAlias.gs
/**
 * Updates the section and room of Google Classroom.
 * @param {string} course_id
 * @see https://developers.google.com/classroom/reference/rest/v1/courses.aliases/create
 */
function addAlias(course_id) {
  const alias = {
    'alias': 'p:bio_101'
  };
  try {
    const course_alias = Classroom.Courses.Aliases.create(resource=alias, courseId=course_id);
    Logger.log('%s successfully added as an alias!', course_alias.alias);
  } catch (err) {
    // TODO (developer) - Handle exception
    Logger.log('Request to add alias %s failed with error %s.', alias.alias, err.message);
  }
}

Python

classroom/snippets/classroom_add_alias_existing.py
def classroom_add_alias_existing(course_id):
    """
        Adds alias to existing 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)
    alias = 'd:school_math_101'
    course_alias = {
            'alias': alias
        }
    try:
        course_alias = service.courses().aliases().create(
            courseId=course_id,
            body=course_alias).execute()
        return course_alias
    except HttpError as error:
        print(f"An error occurred: {error}")
        print('Alias Creation Failed')
    return course_alias


if __name__ == '__main__':
    # Put the course_id of course whose alias needs to be added.
    classroom_add_alias_existing(456058313539)

Retrieve course aliases

You can retrieve the aliases for a course using the courses.aliases.list() method, as shown in the following sample:

.NET

classroom/snippets/ClassroomSnippets/ListCourseAliases.cs
using System;
using System.Collections.Generic;
using Google;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Classroom.v1;
using Google.Apis.Classroom.v1.Data;
using Google.Apis.Services;

namespace ClassroomSnippets
{
    // Class to demonstrate the use of Classroom List Alias API
    public class ListCourseAliases
    {
        /// <summary>
        /// Retrieve the aliases for a course.
        /// </summary>
        /// <param name="courseId">Id of the course.</param>
        /// <returns>list of course aliases, null otherwise.</returns>
        public static List<CourseAlias> ClassroomListAliases(string courseId)
        {
            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.ClassroomCourses);

                // Create Classroom API service.
                var service = new ClassroomService(new BaseClientService.Initializer
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "Classroom Snippets"
                });

                string pageToken = null;
                var courseAliases = new List<CourseAlias>();

                do
                {
                    // List of aliases of specified course
                    var request = service.Courses.Aliases.List(courseId);
                    request.PageSize = 100;
                    request.PageToken = pageToken;
                    var response = request.Execute();
                    courseAliases.AddRange(response.Aliases);
                    pageToken = response.NextPageToken;
                } while (pageToken != null);

                if (courseAliases.Count == 0)
                {
                    Console.WriteLine("No aliases found.");
                }
                else
                {
                    Console.WriteLine("Aliases:");
                    foreach (var courseAlias in courseAliases)
                    {
                        Console.WriteLine(courseAlias.Alias);
                    }
                }
                return courseAliases;
            }
            catch (Exception e)
            {
                // TODO(developer) - handle error appropriately
                if (e is AggregateException)
                {
                    Console.WriteLine("Credential Not found");
                }
                else if (e is GoogleApiException)
                {
                    Console.WriteLine("Course does not exist.");
                }

                else
                {
                    throw;
                }
            }
            return null;
        }
    }
}

Java

classroom/snippets/src/main/java/ListCourseAliases.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.CourseAlias;
import com.google.api.services.classroom.model.ListCourseAliasesResponse;
import com.google.auth.http.HttpCredentialsAdapter;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/* Class to demonstrate the use of Classroom List Alias API */
public class ListCourseAliases {
  /**
   * Retrieve the aliases for a course.
   *
   * @param courseId - id of the course.
   * @return list of course aliases
   * @throws IOException - if credentials file not found.
   */
  public static List<CourseAlias> listCourseAliases(String courseId)
      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_COURSES));
    HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(
        credentials);

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

    String pageToken = null;
    List<CourseAlias> courseAliases = new ArrayList<>();

    try {
      // List of aliases of specified course
      do {
        ListCourseAliasesResponse response = service.courses().aliases().list(courseId)
            .setPageSize(100)
            .setPageToken(pageToken)
            .execute();
        courseAliases.addAll(response.getAliases());
        pageToken = response.getNextPageToken();
      } while (pageToken != null);

      if (courseAliases.isEmpty()) {
        System.out.println("No aliases found.");
      } else {
        System.out.println("Aliases:");
        for (CourseAlias courseAlias : courseAliases) {
          System.out.println(courseAlias.getAlias());
        }
      }
    } catch (GoogleJsonResponseException e) {
      // TODO(developer) - handle error appropriately
      GoogleJsonError error = e.getDetails();
      if (error.getCode() == 404) {
        System.err.println("Course does not exist.\n");
      } else {
        throw e;
      }
    }
    return courseAliases;
  }
}

Python

classroom/snippets/classroom_list_course_aliases.py
from __future__ import print_function

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError


def classroom_list_course_aliases(course_id):
    """
    Prints the list of the aliases of a specified course 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)
        course_aliases = []
        page_token = None

        while True:
            response = service.courses().aliases().list(
                pageToken=page_token,
                courseId=course_id).execute()
            course_aliases.extend(response.get('aliases', []))
            page_token = response.get('nextPageToken', None)
            if not page_token:
                break

        if not course_aliases:
            print('No course aliases found.')

        print("Course aliases:")
        for course_alias in course_aliases:
            print(f"{course_alias.get('alias')}")
        return course_aliases
    except HttpError as error:
        print(f"An error occurred: {error}")
        return error


if __name__ == '__main__':
    classroom_list_course_aliases('course_id')