google classroom.create 的正确 JSON 格式是什么?

What is the correct JSON format for googles classroom.create?

我正在尝试使用 google 教室创建教室 API。每当 运行 classroom.create 函数时,我总是收到相同的错误消息。我正在使用他们文档中的 JSON 格式,但我无法让它工作。我想我一定是漏掉了什么。

这是函数:

async function listCourses(auth) {
const classroom = google.classroom({ version: 'v1', auth });
//Read data from JSON
let data = fs.readFileSync("class.json");
let course = JSON.parse(data);
//Try and create course
try {
    const res = await classroom.courses.create(course);
    console.log(res.data);
}
catch (error) {
    console.log(error)
}
//List all current courses
classroom.courses.list({
    pageSize: 10,
}, (err, res) => {
    if (err) return console.error('The API returned an error: ' + err);
    const courses = res.data.courses;
    if (courses && courses.length) {
        console.log('Courses:');
        courses.forEach((course) => {
            console.log(`${course.name} (${course.id})`);
        });
    } else {
        console.log('No courses found.');
    }
});

}

这是JSON:

{
"id": "157942918368",
"name": "English - 9Y",
"section": "Period 2",
"ownerId": "me",
"courseState": "ACTIVE"

}

这是错误信息:

 code: 400,
 errors: [
{
  message: `Invalid JSON payload received. Unknown name "name": Cannot bind query parameter. Field 'name' could not be found in request message.\n` +
    `Invalid JSON payload received. Unknown name "ownerId": Cannot bind query parameter. Field 'ownerId' could not be found in request message.\n` +
    `Invalid JSON payload received. Unknown name "courseState": Cannot bind query parameter. Field 'courseState' could not be found in request message.\n` +
    `Invalid JSON payload received. Unknown name "id": Cannot bind query parameter. Field 'id' could not be found in request message.\n` +
    `Invalid JSON payload received. Unknown name "section": Cannot bind query parameter. Field 'section' could not be found in request message.`,
  reason: 'invalid'
}

]

我相信你的目标如下。

  • 您想使用 googleapis 为 Node.js 创建新课程。

修改点:

  • 在 googleapis for Node.js,请将请求正文放入 resource and/or requestBody
    • 我认为你的错误信息的原因是由于这个。
  • 使用"id": "157942918368",时,出现Request contains an invalid argument.的错误。
  • 使用"courseState": "ACTIVE"时,会出现"@CourseStateDenied This user cannot create or transition courses into the requested state."的错误。
    • 在这种情况下可以使用“PROVISIONED”。

当以上几点反映到你的脚本中,就变成了下面这样。

修改后的脚本:

发件人:

const res = await classroom.courses.create(course);

收件人:

const res = await classroom.courses.create({ requestBody: course });

const res = await classroom.courses.create({ resource: course });

另外,请修改您的请求正文如下。

发件人:

{
  "id": "157942918368",
  "name": "English - 9Y",
  "section": "Period 2",
  "ownerId": "me",
  "courseState": "ACTIVE"
}

收件人:

{
  "name": "English - 9Y",
  "section": "Period 2",
  "ownerId": "me",
}

注:

  • 在本次修改中,假设您的const classroom = google.classroom({ version: 'v1', auth });可以在课堂API中使用courses.create的方法。

参考文献: