Search code examples
google-apps-scriptgoogle-classroom

Adding a Topic ID to a Google Classroom assignment


I'm trying to create an assignment using Google Apps script and place it under a topic that is also created in the same script. I have no problem creating an assignment when no topicId is specified, but as soon as I try to specify a topicId , I receive the following error when I run the script: API call to classroom.courses.courseWork.create failed with error: Invalid JSON payload received. Unknown name "Test Topic"

Here is my code:

function makeStuff() {

  var topic = { 
    name: "Test Topic"
  };
  Classroom.Courses.Topics.create(topic, "46088716060");               

  var TWS1 =  {
    title: "Test Worksheet 1",
    state: "DRAFT",
    materials: [
      {
        driveFile:{
        driveFile: {
          id: "1REOs1RYtyVTX67VnJezjWf-wm7HqDVexeaeiQL3-HvM", 

        },
        shareMode: "STUDENT_COPY"
        }

      }
      ],
    workType: "ASSIGNMENT",
    topicId: {
    name: "Test Topic"
    }

  };

  Classroom.Courses.CourseWork.create(TWS1, "46088716060") 
}

Is it possible to reference the topicId by name, or assign the topicId number that is created in the script to a variable that can be referenced?


Solution

  • To create a topic, you only need to supply a name (the topic name is not its id, only the API can generate ids). The Classroom API then creates the topic, which it returns as an object with the topicId property defined on it, as seen below;

    var courseId = "46088716060";
    var topicName = "Test Topic";
    
    var topic = Classroom.Courses.Topics.create({name:topicName}, courseId);
    var topicId = topic.topicId;
    
    

    You then use that topicId when creating coursework.