How to connect to Google Drive API with a Node.js application

Google Drive API allows you to read, write and sync files in Google Drive using your application. You can download and upload files, as well as search files and folders stored in Google Drive.

You need to have the following, before getting started:

  1. Google account
  2. Node js installed

Create a new folder for your project and run ‘npm-init’. Once done, create a file in your root directory name it as ‘app.js’.

Next, log in to your google account and visit console.developers.google.com. Create a new project. Enter a suitable project name.

Create project

Click on ENABLE APIS AND SERVICES and search for Google Drive API. You need to enable this API, before getting started.

Enable api

You need to create a service account to move further. Click on the Credentials tab from the left sidebar menu.

Credentials

 Next, click on CREATE CREDENTIALS, select service account.

Service account

You will be asked to enter service name. A service ID will be created, click on create and fill in all the other details which are optional. Click on DONE and you will be directed to the main page. In the service account section click on the newly created ID. You will be redirected to a page that will display service details, status and key. Select Add key and then select Create new key -> key type: JSON and click on CREATE

Key

JSON file will be downloaded in your system. We will have to use this file in our project for authentication purposes. Rename this file to ‘keys.json’. JSON file will have the following structure:

JSON file

Once this is done, we can now start writing the code. We need to install Google Api module in our project. Open the terminal, make sure you’re in the project folder, and install packages. Run the following commands in the terminal

npm i express

npm i googleapis

npm i async

Create a file with name ‘app.js’. We can start writing code now. Lets begin by writing following piece of code.

In ‘app.js’ file write the following code.


const express = require('express');
const { google } = require("googleapis");
const keys = require("./keys.json");
var async = require("async");
var app = express();

const scopes = [
'https://www.googleapis.com/auth/drive'
];
const client = new google.auth.JWT(keys.client_email, null, keys.private_key,scopes);

client.authorize(function (err) {
    if (err) {
        console.log(new Error("Error:", err));
        return;
    } else {
        console.log("Connection established with Google API");
    }
});

let getlist = (client) => {
    const drive = google.drive({ version: "v3", auth:client });
    const response =  drive.files.list({
            pageSize: 10,
            fields: 'nextPageToken, files(id, name)',
    }, (err, res) => {
            if (err) return console.log('The API returned an error: ' + err);
            const files = res.data.files;
            if (files.length) {
              console.log('Files:');
              files.map((file) => {
              console.log(`${file.name} (${file.id})`);
              });
            } else {
              console.log('No files found.');
            }
    });
 }

app.listen(5000, function () {
console.log("Server is ready!");
})
getlist(client)

Specify number of files to be displayed per page using ‘pageSize’ and to fetch details of files make use of ‘fields’. If you want to fetch all the fields of file then use ->  fields: ‘*’. If you want to fetch url of the file then use -> fields: ‘files(webViewLink)’. If you need to sort the list then use -> orderBy: ‘createdTime desc’.

Run your project through terminal using command ‘node app.js’.