Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created Jun 29, 2020
Embed
What would you like to do?
Report: Processing to Create New File to Specific Folder using Drive API

Report: Processing to Create New File to Specific Folder using Drive API

In this report, I would like to report for processing to create new file to the specific folder using Drive API. When the new file is created to the specific folder using Drive API, the property of parents with the value of folder ID is included in the request body of the method "Files: create". About this process, I had thought that the file is directly created to the specific folder. But, I could confirm that the new file is created by the following process.

  1. Create new file to the root folder.
  2. Move the created file to the specific folder.

These process is done by one API call. In this report, I would like to introduce the experimental result for confirming above process. In this case, Drive API v3 is used with Google Apps Script.

Sample script

The sample script is as follows. "BatchRequest" of the Google Apps Script library was used. This sample script creates 5 new Spreadsheet files to the specific folder using the batch request.

function createFilesInFolders() {
  const reqs = [];
  for (let i = 0; i < 5; i++) {
    reqs.push({
      method: "POST",
      endpoint: "https://www.googleapis.com/drive/v3/files",
      requestBody: {
        name: `sampleFile_${i + 1}`,
        mimeType: MimeType.GOOGLE_SHEETS,
        parents: ["folderId"],
      },
    });
  }
  const requests = {
    batchPath: "batch/drive/v3",
    requests: reqs,
  };
  const result = BatchRequest.EDo(requests);
  console.log(result);
}

Result

This figure shows the situation that the script is run. When the script is run, it is found that 5 new Spreadsheet files are created to the root folder, and then, the files are moved to the specific folder. From this result, it was found that when new file is created to the specific folder with the method "Files: create" of Drive API, the file is created to the root folder and moved to the specific folder by one API call.

When only 1 file is created by one API call, it is considered that the file created to the root folder couldn't be seen because of the update speed of Google Drive. It is considered that using the batch request, this situation could be confirmed.

Reference

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