Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active December 29, 2022 16:52
Show Gist options
  • Save tanaikech/bac38226e863a398f55b5c3d817d86ed to your computer and use it in GitHub Desktop.
Save tanaikech/bac38226e863a398f55b5c3d817d86ed to your computer and use it in GitHub Desktop.
Using Google Forms API with Google Apps Script

Using Google Forms API with Google Apps Script

On October 12, 2021, Google Forms API had been announced. Ref On December 7, 2021, Google Forms API had been released as open beta. Ref In the current stage, when the users join the Early Adopter Program, they can use Google Forms API of the beta version. Ref

By using Google Forms API, what Google Forms service cannot achieve got to be able to be achieved by Google Forms API. In this report, I would like to introduce how to use Google Forms API and the sample script of the situations which cannot be achieved by Google Forms service.

Usage

1. Join Early Adopter Program.

In the current stage, in order to use Google Forms API beta, please join Early Adopter Program. Ref

When Google Forms API is released as the alpha version, this process can be skipped.

2. Link Google Cloud Platform Project to Google Apps Script Project.

In the current stage, Google Forms API cannot be used with Advanced Google services. So please link Google Cloud Platform Project to Google Apps Script Project. Ref And also, please enable Google Forms API at API console.

Also, I believe Google Forms API might be able to be used with Advanced Google services. At that time, this process can be skipped.

3. Scopes

In this sample script, the scope of https://www.googleapis.com/auth/forms.body is used for using Google Forms API. And, Drive API uses the scope of https://www.googleapis.com/auth/drive.metadata.readonly, and UrlFetchApp uses https://www.googleapis.com/auth/script.external_request.

4. Sample script.

This script also uses Drive API. So please enable Drive API at Advanced Google services before you use this script.

Please copy and paste the script editor of Google Apps Script lining with Google Cloud Platform Project.

// 1. Create new Google Form.
function createNewGoogleForm_(title) {
  const res = UrlFetchApp.fetch("https://forms.googleapis.com/v1beta/forms", {
    method: "post",
    headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() },
    contentType: "application/json",
    payload: JSON.stringify({ info: { title } }),
  });
  const obj = JSON.parse(res.getContentText());
  return obj.formId;
}

// 2. Add questions.
function addQuestions_(formId) {
  const imageFileIds = [
    "### FileId1 of image file on Google Drive ###",
    "### FileId2 of image file on Google Drive ###",
  ];
  const [imageUrl1, imageUrl2] = imageFileIds.map((id) =>
    Drive.Files.get(id, { fields: "thumbnailLink" }).thumbnailLink.replace(
      "=s220",
      "=s500"
    )
  );

  // Dropdown list.
  const question1 = {
    createItem: {
      item: {
        title: "Sample Choice Question",
        questionItem: {
          question: {
            choiceQuestion: {
              type: "DROP_DOWN",
              options: ["value1", "value2", "value3"].map((e) => ({
                value: e,
              })),
            },
          },
          image: { altText: "sample", sourceUri: imageUrl1 },
        },
      },
      location: { index: 0 },
    },
  };

  // Text input.
  const question2 = {
    createItem: {
      item: {
        title: "Sample Text Question",
        questionItem: {
          question: { textQuestion: { paragraph: false } },
          image: { altText: "sample", sourceUri: imageUrl2 },
        },
      },
      location: { index: 1 },
    },
  };

  const url = `https://forms.googleapis.com/v1beta/forms/${formId}:batchUpdate`;
  return UrlFetchApp.fetch(url, {
    method: "post",
    headers: { authorization: "Bearer " + ScriptApp.getOAuthToken() },
    contentType: "application/json",
    payload: JSON.stringify({ requests: [question1, question2] }),
  });
}

// Please run this function.
function main() {
  // 1. Create new Google Form.
  const formId = createNewGoogleForm_("sample form");

  DriveApp.getFileById(formId).setName("sample form"); // In the current stage, the created Google Form has no filename. So it is required to use this line. I have already reported this. https://issuetracker.google.com/issues/207158296

  // 2. Add questions.
  const res = addQuestions_(formId);
  console.log(res.getContentText());
}

5. Testing.

When the above script is run, a new Google Form is created including 2 questions as shown in the image of top of this report. You can see that the image is added to the title of each question. In the current stage, the image cannot be added to the title of question using Google Forms service. This can be achieve using Google Forms API.

(The above images are from http://k3-studio.deviantart.com/.)

Note

  • When I posted this report, Google Forms API is the beta version. So the endpoint is like https://forms.googleapis.com/v1beta/forms/. When Forms API is released as the alpha version (version 1), I think that it will be https://forms.googleapis.com/v1/forms/. At that time, please check the official document. Ref

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment