Workaround: Checking Existence of File ID in Google Drive without Access token and API key

Gists

This is a workaround for checking the existence of file ID in Google Drive without both the access token and API key.

When you want to check whether the file of the file ID is existing in Google Drive, generally, you might use Drive API and Drive service (DriveApp) of Google Apps Script. In this case, the scope of Drive API is required to be used. By this, the access token and the API key (in the case of publicly shared files) are required to be used. But, there might be a case that the available scopes are limited. In this post, I would like to introduce a workaround for checking the existence of file ID in Google Drive without both the access token and API key.

Workaround: curl

In this workaround, the thumbnail link like https://drive.google.com/thumbnail?id={fileId} is used. Ref In this case, when the file ID is existing, the sign-in page with the status code of 200 is returned. On the other hand, when the file ID is not existing, an error like Error 404 (Not Found) with the status code of 404 occurs. This workaround uses this situation. A sample curl command is as follows. Please replace {fileId} with a sample file ID.

$ curl -L -s "https://drive.google.com/thumbnail?id={fileId}" -o /dev/null -w '%{http_code}'
  • When the valid file ID is used as {fileId}, you can see the status code of 200 in the terminal.
  • When the invalid file ID is used as {fileId}, you can see the status code of 404 in the terminal.

By this, you can see whether the file ID is existing.

Workaround: Google Apps Script

When this workaround is used with Google Apps Script, the script is as follows.

const SAMPLE = (id) =>
  UrlFetchApp.fetch(`https://drive.google.com/thumbnail?id=${id}`, {
    muteHttpExceptions: true,
  }).getResponseCode() == 200
    ? true
    : false;

In this case, for example, you can use this script as a custom function of Google Spreadsheet like =SAMPLE("###fileId###"). So, you can check whether the file ID is existing with a custom function.

Reference

 Share!