Sunday, June 9, 2019

Google Drive API Javascript Example

On this tutorial, we gonna use Google Drive API for Javascript. We use NodeJS on this tutorial, so you must have NodeJS installed in your PC/Laptop.

For the API authentication, go to and choose your option. You can authenticate with API key, or by Oauth 2.0, and by Service Account. Your authentication is almost ready, you have to enable Google API you want to use, by visiting Google API Library and enable Google Drive API.

Follow this step to use Google Drive API.

1. Share Files

To use the service account method of authentication, you’ll need to provide access to the service account. You can provide access on a file-by-file basis or at the level of folders. Find the "client_email" key in your credientials.json file and copy the value. This is the email address that you’ll need to share, and it will look something like:

Create a new folder in your account’s Google Drive, and then share it with the "client-email" in your credentials.json . Sharing access to the service account is required, and it’s one of the reasons a service account is more secure than a simple API key.

2. Install Google API packages

Open the terminal, making sure you’re in the project directory, and type npm i googleapis . The conventional way to import the module into a Node.js file is like this:

const { google } = require('googleapis');

3. Start Coding

Load the Google API library, read your credential.json files and use Google Drive scopes. We'll using Google Auth with JWT for this tutorial:

const { google } = require('googleapis');
const credentials = require('./credentials.json');
const scopes = [ '' ];
const auth = new google.auth.JWT( credentials.client_email, null, credentials.private_key, scopes );

test your code with listing all files from your Drive account:

drive.files.list({}, (err, res) => {
if (err) throw err;
const files =;
if (files.length) { => {
} else {
console.log('No files found');


Post a Comment