Tuesday 16 January 2024

Drive API - get file information

The following Google Apps Script is a snippet of code where I was learning how to use the Drive API to query a folder of files, to extract some specific file information. It is designed to work on both My/Shared drives.

Information to Extract

  • Name;
  • Type (e.g. Doc, Sheet);
  • ID;
  • Creation date;
  • Last modified date;
  • Clickable link;
  • Owners

Enable Drive API

Please follow the steps to enable the 'Drive API' Service if you are not working from a copy of the file in this post.

The Code

The trickiest part of this code was getting the correct query parameters to make the Drive API call and only return the data we wanted, as opposed to returning everything and sorting through it all. We include support for Shared drives here too:

var payload =
    'q': `'${folderId}' in parents and trashed=false`,
: `items(title, mimeType, id, createdDate, modifiedDate, alternateLink, owners)`,
: true,
    'includeItemsFromAllDrives': true

Next we can make the call and get the item details returned:

var response = Drive.Files.list(payload);
var fileItems = response.items;

Given we have a folder full of files we now need to loop through each item:

 for (var i = 0; i < fileItems.length; i++) {

    // get individual details for a single file
    var fileInfo = fileItems[i];
    console.log("File info is: " + fileInfo);

Getting the owners involves a few more steps:

// get all owners of the file
var allOwners = fileInfo.owners;
console.log("allOwners is: " + allOwners);

// convert the data to a JavaScript Object so it can be queried
var cleanData = JSON.parse(allOwners);

// get the email address of the owner
var ownerEmailAddress = cleanData.emailAddress;
console.log("ownerEmailAddress is: " + ownerEmailAddress);

And there we have it!


Drive API - get file information download (please use 'Overview' > 'Make a copy' for your own version).

No comments:

Post a Comment