what can i do to add a file on my drive using drive api v3?

Use Google Drive’s new shortcut MIME type! You can reference Google’s example Create a shortcut to a Drive file for hints. Keep in mind that Advanced Drive Services is limited to Drive API v2, but URLFetchApp can also use Drive API v3.

The code below is for URLFetchApp. If you would rather use Advanced Drive Service, see this answer instead: How to create a shortcut in Google Drive Apps Script instead of multiple parents

/*
 * Create a new shortcut using UrlFetchApp.
 *
 * @param {String} driveId    Id of the file/folder to use as a shortcut target.
 * @param {String} userEmail  User email address for change context and OAuth token.
 * @param {String} parentId   The parent folder for the shortcut file.
 * @param {String} driveName  The display name of the shortcut.
 * https://developers.google.com/drive/api/v3/shortcuts
 * https://developers.google.com/drive/api/v3/reference/files/create
 * https://github.com/googleworkspace/apps-script-oauth2
 */
function TEST_addShortcut() { addShortcut('DriveKey0123456789ABCDEabcde',
                                          '[email protected]',
                                          'root',
                                          'The file or folder name')
};

function addShortcut(driveId, userEmail, parentId, driveName) {
  var service = getService(userEmail); //apps-script-oauth2 library
  if (service.hasAccess()) {
    Logger.log("addShortcut hasAccess, User %s",userEmail);
    
    var url = 'https://www.googleapis.com/drive/v3/files/';
    var data = {
      'shortcutDetails': {'targetId': driveId},
      'name'       : driveName,
      'mimeType'   : 'application/vnd.google-apps.shortcut',
      'parents'    : parentId //Use Id 'root' for user's My Drive folder
    };
    var options = {
      'method'     : 'POST',
      'contentType': 'application/json',
      'headers'    : { Authorization: 'Bearer ' + service.getAccessToken() },
      'payload'    : JSON.stringify(data) // Convert JavaScript object to JSON string
    };
    
    var response = UrlFetchApp.fetch(url, options);
    var resultStringy = JSON.stringify(response, null, 2);
    var respCode = response.getResponseCode()
    Logger.log('addShortcut code %s, result: %s', respCode, resultStringy);
    return (respCode == 200);
    
  } else {
    
    Logger.log('addShortcut getLastError: %s', service.getLastError());
    Logger.log('addShortcut(%s) = %s',userEmail,'No Access');
    return null; //Service does not have access
  }
};

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top