Search code examples
google-apps-scriptgoogle-apishortcut

Creating a Google Document shortcut in a G suite shared drive using Google App Script


I am able to easily create shortcuts to Google Document files, with the shortcut in My Drive, or a folder within My Drive. This was helped greatly by this question and response How to create a shortcut in Google Drive Apps Script instead of multiple parents

However, when I try and do the same with a G Suite shared Drive folder, I am given the following error:

GoogleJsonResponseException: API call to drive.files.insert failed with error: File not found: #FILE NUM

The code, as working with My Drive, but not a shared drive is:

function createShortcut() {

  const targetId = "TARGET DOCUMENT ID"; 
  const shortcutName = "Test"; 
  const folderId = "TARGET FOLDER ID";
 
  const resource = {
    shortcutDetails: { targetId: targetId },
    title: shortcutName,
    mimeType:"application/vnd.google-apps.shortcut",
    supportsTeamDrives:true,
    parents: [{id: folderId}]
  };

  const shortcut = Drive.Files.insert(resource);
}

I have consulted the documentation: https://developers.google.com/drive/api/v3/shortcuts with no luck.


Solution

  • Problem

    You are including the supportsTeamDrives parameter in the File resource. First, this parameter is deprecated as shown in the documentation: you shall now use supportsAllDrives. Second, there is a difference between request body (the one you called resource) and request parameters.

    Solution

    If you look at the Drive.Files.insert() functions signatures you will see that there are 3 options:

    • .insert(File resource);
    • .insert(File resource, Blob mediaData);
    • .insert(File resource, Blob mediaData, Object optionalArgs);

    You are using the first one and this doesn't allow to specify any request parameters. You should therefore use the third one.

    Here is how to use it in your case:

    // Since you are not creating nor uploading any file you shall leave the Blob mediatada parameter as null
     const resource = {
        shortcutDetails: { targetId: targetId },
        title: shortcutName,
        mimeType:"application/vnd.google-apps.shortcut",
        parents: [{id: folderId}]
      };
      
      const options = { supportsAllDrives: true };
    
      const shortcut = Drive.Files.insert(resource, null, options);
    

    Reference

    Files v2 insert