Electric Dragon
Electric Dragon

Reputation: 366

How to get the assignment title from Google Classroom with Python

I want to get the assignment title of each assignment posted by the teacher in a specific course in Google Classroom. Can someone help me with this? When I try the API explorer on the official website, it returns the correct result but it doesn't work with my python file.

    service = build('classroom', 'v1', credentials=creds)

    # Call the Classroom API
    results = service.courses().courseWork().get(courseId).execute()
    courses = results.get('courses')

    if not courses:
        print('No courses found.')
    else:
        print('Courses:')
        for course in courses:
            print(course)

Upvotes: 1

Views: 582

Answers (2)

Abhinav Mathur
Abhinav Mathur

Reputation: 8101

In order to access the coursework, you have to edit the predefined SCOPE in the sample code provided (and also delete the token.pickle file).
Check this, for a better understanding.

Upvotes: 1

Iamblichus
Iamblichus

Reputation: 19309

While you already accepted an answer, I think other people with your same problem might not be able to solved their issue based on that. Therefore, I'm posting an answer too.

Use correct parameters for "get" method:

You didn't specify which specific problem you had / what error were you getting (you just said it doesn't work), but the code you shared is not correct:

If you want to use courses.courseWork.get, you have to provide at least two parameters, for courseId and for id (referred to the assignment id), so it should be like this:

service.courses().courseWork().get(courseId=courseId, id=courseWorkId).execute()

Use "list" instead of "get":

But since you want to get the assignment titles of all the assignments in the course (and not for a single assignment), you should be using courses.courseWork.list instead. Your code should be something like this (where title is the title of each assignment):

courseWorkList = service.courses().courseWork().list(courseId=courseId).execute()
for courseWork in courseWorkList["courseWork"]:
    title = courseWork["title"]
    print(title)

And if the number of assignments is very large, you might need to use pageToken and nextPageToken, and call this method in a loop.

Use appropriate scopes:

If you're using list, you need to specify any of these scopes. Otherwise, you are not authorized to access this resource:

https://www.googleapis.com/auth/classroom.coursework.students.readonly
https://www.googleapis.com/auth/classroom.coursework.me.readonly
https://www.googleapis.com/auth/classroom.coursework.students
https://www.googleapis.com/auth/classroom.coursework.me

Reference:

Upvotes: 2

Related Questions