Search code examples
google-classroom

How to get the course ID for Google Classroom API


I'm trying to use Google Classroom API, I've read through their documentation, and the course ID is used for basically everything, but they never explained where to find the course ID for a course.

It also seems like when you create a course, the function would return the course ID, but I'm wondering if it's possible to get the course ID for courses that already exist.


Solution

  • As shown in the quickstart page for the documentation (https://developers.google.com/classroom/quickstart/python), you can run a piece of code to list the first 10 courses the user has access to with their credentials. You can then add a print(course['id']) statement whilst iterating through the courses to print the id of the courses you have retrieved. The python example is shown below

    from __future__ import print_function
    import pickle
    import os.path
    from googleapiclient.discovery import build
    from google_auth_oauthlib.flow import InstalledAppFlow
    from google.auth.transport.requests import Request
    
    # If modifying these scopes, delete the file token.pickle.
    SCOPES = ['https://www.googleapis.com/auth/classroom.courses.readonly']
    
    def main():
        """Shows basic usage of the Classroom API.
        Prints the names of the first 10 courses the user has access to.
        """
        creds = None
        # The file token.pickle 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.pickle'):
            with open('token.pickle', 'rb') as token:
                creds = pickle.load(token)
        # 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.pickle', 'wb') as token:
                pickle.dump(creds, token)
    
        service = build('classroom', 'v1', credentials=creds)
    
        # Call the Classroom API
        results = service.courses().list(pageSize=10).execute()
        courses = results.get('courses', [])
    
        if not courses:
            print('No courses found.')
        else:
            print('Courses:')
            for course in courses:
                print(course['name'])
                print(course['id'])
    
    if __name__ == '__main__':
        main()