Creating Quizzes in Google Form using Google Forms API with Google Apps Script

Gists

This is a sample script for creating quizzes in Google Form using Google Forms API with Google Apps Script. Recently, Google Forms API has been officially published, and it got to be able to be used by users. By this, quizzes in Google Form can be created using Google Forms API.

Here, there is one thing that can be achieved by Google Forms API. When Google Forms API is used, each choice in each question can be shuffled. This cannot be achieved with Google Forms Service (FormApp).

Usage

1. Linking Google Cloud Platform Project to Google Apps Script Project for New IDE.

In order to use Forms API, please link Google Cloud Platform Project to Google Apps Script Project for New IDE, and please enable Forms API at API console. Ref

2. Prepare questions and answers.

In this sample, the questions and answers are prepared using Spreadsheet as follows.

2. Sample script.

function createQuize_forPublish() {
  const ssId = "###"; // Please set Spreadsheet ID.
  const sheetName = "Sheet1"; Please set sheet name including questions and answers like the above image.
  const formTitle = "sample"; // This is a title of Google Form.

  // Create new Google Form and set as quizzes.
  const form = FormApp.create(formTitle);
  const formId = form.getId();
  form.setIsQuiz(true);
  form.setShuffleQuestions(true);
  form.setProgressBar(true);
  form.setTitle("Sample questions");

  // Retrieve questions and answers from Spreadsheet.
  const sheet = SpreadsheetApp.openById(ssId).getSheetByName(sheetName);
  const [, ...values] = sheet.getDataRange().getDisplayValues();
  const obj = values.map(([aa, bb, cc]) => {
    const ans = cc.split(",").map(e => e.trim());
    return { q: aa, a: bb.split("\n").map(e => e.trim()), ans, type: ans.length == 1 ? "RADIO" : "CHECKBOX" };
  });

  // Create request body for Google Forms API.
  const url = `https://forms.googleapis.com/v1/forms/${formId}:batchUpdate`;
  const requests = obj.map(({ q, a, ans, type }, index) => ({
    createItem: {
      item: {
        title: q,
        questionItem: { question: { choiceQuestion: { options: a.map(value => ({ value })), shuffle: true, type }, grading: { correctAnswers: { answers: ans.map(e => ({ value: a[e - 1] })) }, pointValue: 1 } } },
      }, location: { index }
    }
  }));

  // Use Google Forms API.
  const params = {
    method: "post",
    contentType: "application/json",
    headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() },
    payload: JSON.stringify({ requests }),
    muteHttpExceptions: true
  };
  const res = UrlFetchApp.fetch(url, params);
  console.log(res.getContentText())
}

Testing.

When this script is run using the prepared Spreadsheet, you can see the result Google Form at the top image in this post.

Note

  • This sample script doesn’t include the error procession. So please add it for your actual situation.

Reference

 Share!