Search code examples
jsongoogle-apps-scriptgoogle-classroom

Attaching a Drive file to an assignment with Google Classroom API


Using Google Apps Script I have managed to create an assignment with the following code:

Classroom.Courses.CourseWork.create({
 "courseId": id,
 "title" : title,
 "description" : desc,
 "workType" : 'ASSIGNMENT',
 }, id)

This works fine, creating a draft assignment on Classroom. However, when I try to attach a Drive file like so:

  Classroom.Courses.CourseWork.create({
    "courseId": id,
    "title" : title,
    "description" : desc,
    "workType" : 'ASSIGNMENT',
    "materials" : [
      {
      "driveFile": {
        "id" : fileId,
        "title" : fileTitle,
        "alternateLink" : fileLink,
        "thumbnailUrl" : fileThumbnail,
      },
      "shareMode" : 'STUDENT_COPY',
    }
    ],
  }, id)

I receive these errors:

Execution failed: Invalid JSON payload received. Unknown name "share_mode" at 'course_work.materials[0]': Cannot find field.

Invalid JSON payload received. Unknown name "alternate_link" at 'course_work.materials[0].drive_file': Cannot find field.

Invalid JSON payload received. Unknown name "id" at 'course_work.materials[0].drive_file': Cannot find field.

Invalid JSON payload received. Unknown name "title" at 'course_work.materials[0].drive_file': Cannot find field.

Invalid JSON payload received. Unknown name "thumbnail_url" at 'course_work.materials[0].drive_file': Cannot find field. (line 61, file "Classroom") [1.187 seconds total runtime]

Any help will be appreciated, thank you


Solution

  • You may refer with this SO answer. This error might happen because of wrong formatting of the request.

    Sample code:

    function myFunction() {
      var ClassSource =  {
        title: "Test File",
        state: "DRAFT",
        materials: [
          {
            driveFile:{
            driveFile: {
              id: "fileID", 
              title: "Sample Document"
    
            },
            shareMode: "STUDENT_COPY"
            }
    
          }
          ],
        workType: "ASSIGNMENT"
      };
    
      Classroom.Courses.CourseWork.create(ClassSource, COURSEID)
      //Logger.log(exec);
    }
    

    You may try this using Try this API.

    Hope this helps!