Google Drive API With Rowy: How To Upload, List, And Share Files (2023)

With its generous free tier including 15 Gb of storage, Google Drive is a great way to store files if you're on a tight budget. In this article, we show you how to use the Google Drive API to manage them from your own custom app.

Use Cases

Google Drive offers free file storage up to 15 Gb. Firebase Cloud Storage is cheap ($0.026 per Gb with 5 Gb free) and easy to use, but maybe you need a user interface like Google Drive's to easily manage files and share file links on the go with teammates. For small usages, using the Google Drive API offers the best balance between cost efficiency and easy collaboration.

Using the Google Drive API is also useful to automate file processing. For example, you might want to optimize uploaded images to reduce their size. This way, you won't need complex tooling whenever a colleague needs to publish an image online. We'll see how to do this in part 4.

1. Enable The Google Drive API In Google Cloud

First, enable the Google Drive API in your Google Cloud console. Just log in your account, search for "Google Drive API", and click the Enable button:

0.webp

Because Rowy is built on top of Firebase, you can use the same Google Cloud account. This saves you the hassle of setting up OAuth2.

Simply create a new Google Drive API client with the desired API scope, and you're good to go:

const drive = require('@googleapis/drive')

const gauth = new gmail.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/drive']
});

const authClient = await gauth.getClient();

const client = await drive.drive({
    version: 'v3',
    auth: authClient
});

2. Upload Files

Rowy handles file uploads for you using Firebase Storage. Simply create a new Rowy column of type File or Image and you'll be able to upload any file you want:

1.webp

Once the upload is complete, you can use the file reference to upload it to Google Drive. For example, using a Rowy Derivative column add the following logic.

const derivative: Derivative = async ({ row, db }) => {
  const drive_file = await client.files.create({
      {
      name: 'photo.jpg',
      fields: 'id',
      },
      media: {
        mimeType: 'image/jpeg',
        body: fs.createReadStream(row.inputFile[0].downloadURL),
      },
    });

  return drive_file.data.id;
}

Once the upload is complete, you can use the Firebase Storage object from any Rowy cloud function to delete it. This way, you won't need to worry about Firebase Storage costs:

const fileRef = storage.ref(storage, row.inputFile[0].downloadURL);

storage.deleteObject(fileRef)

3. List Files

Uploaded file metadata can be accessed with the files.get method, using the returned fileId:

const file = await client.files.get({
    fileId: row.fileId
}).then(res => res.data)

To search several files, you can use the files.list method. For example, to list all jpeg images in your Drive:

const files = await client.files.list({
    pageSize: 10,
    q: 'mimeType=\'image/jpeg\'',
    fields: 'nextPageToken, files(id, name)',
}).then(res => res.data.files)

If you don't include a q parameter, the method will return all files in your Drive.

Note that the returned files belong to the authenticated user. To interact with Google Cloud, Rowy leverages service accounts in the form of <id>@<project id>.iam.gserviceaccount.com: this is different from your regular Google Drive account!

If you wish to interact with a shared Drive account, you can use the driveId field in any Drive API method. Note that you need the proper access rights for this.

4. Processing Files With Google Cloud Functions

Of course, one of the main benefits of using an API is the ability to automate repetitive tasks. For example, we can use the Drive API to optimize images for publishing.

First, we can obtain the file data in a Byte format using the files.export method:

const inputBuffer = await client.files.export({
    fileId: row.fileId,
    mimeType: 'image/png'
});

Then, we can use an image processing library to change the file format, decrease the image resolution, or crop to a desired image ratio:

const sharp = require('sharp');

sharp(inputBuffer)
  .resize(320, 240)
  .toFile('output.webp', (err, info) => { ... });

You can also edit documents to conform to company guidelines, rename files to follow a naming convention, convert PDF files to plain text, etc. Anything is possible!

5. Share files

At some point, you might want to share files with other users. Or make them public.

First, you'll need to adjust the permission rights to suit your use case. For example, to give anyone read access:

const permissions = [
    {
      type: 'anyone',
      role: 'reader'
    }
];


const result = await client.permissions.create({
    resource: permissions,
    fileId: row.fileId,
    fields: 'id',
});

Then, you can use the file's web view link to share it online. Say, you have an image to share on a website:

const file = await client.files.get({
    fileId: row.fileId
}).then(res => res.data)

6. Manage File Folders

Once you have a lot of files in your Drive, you might want to organize them in folders.

Google Drive considers folders as separate files. You can create a folder by creating a new file with the mimeType set to application/vnd.google-apps.folder:

const fileMetadata = {
    name: 'images',
    mimeType: 'application/vnd.google-apps.folder',
};

const file = await client.files.create({
    resource: fileMetadata,
    fields: 'id',
});

const folderId = file.data.id

Note that the root folder of your Drive is simply aliased as root.

To move a file to a folder, you need to get the file's current parent folder and remove it from the list of parents:

const file = await client.files.get({
    fileId: row.fileId,
    fields: 'parents'
})

const previousParents = file.data.parents.map(parent => parent.id).join(',')

const files = await client.files.update({
    fileId: row.fileId,
    addParents: folderId,
    removeParents: previousParents,
    fields: 'id, parents'
})

Join Rowy On Discord

If you liked this Google Drive API tutorial, you might want to combine it with the Google Sheets or Google Docs APIs to get the most out of your Google files.

If you find any issue with this article, or if you have any questions, feel free to join our Discord server to talk with us. We are a friendly group of makers who love to tinker with APIs using low-code!

Get started with Rowy in minutes

Continue reading

Browse all