Table of contents

Introduction :

Welcome brave coder, In this comprehensive guide we will delve into utilizing the Google Drive API to store and retrieve files programmatically. From setting up authentication to performing CRUD (Create, Read, Update, Delete) operations on files, I will walk you through each stage of the process. First we will do the necessary setup required for using google cloud api and then do the coding part .

You will see number of blogs and videos for implementating google drive api so everything is common in that implementation except authentication. I have implementated using JWT authentication which does not required to authenticate token every time , instead we will use private key to be able to communicate with api.

So for easy understanding of flow I have divided this implementation into two parts :-

PART — 1

Let’s start with setting up App on google cloud console and then enable google drive api to be able to use it.

step-1 ) Login to Google Cloud Console and enable google drive api.

step-2 ) Create service account for your project and generate credentials to be able to connect it with api.

step-3) Create new folder in your google drive and share that folder to service account email.

PART — 2

Now that we are done with initial setup of google cloud app and api now we can jump into coding part to be able to use google api.

Let’s first install npm package for using google services

npm install googleapis

We will be using Google Auth Library for connecting our nodejs app with google api. Below code will JWT (JSON Web Token) client for authentication with the Google Drive API in a Node.js environment.

We will import necessary variables from env. Then we create jwt auth using google.auth.jwt(). After that we create new instance of the Google Drive API using the google.drive() method.

import { google } from 'googleapis' // import necessary credentials from .env file const client_email = process.env.GOOGLE_DRIVE_SERVICE_EMAIL; const private_key = process.env.GOOGLE_DRIVE_PRIVATE_KEY; const SCOPES = ["https://www.googleapis.com/auth/drive.file"]; const jwtClient = new google.auth.JWT( client_email, null!, private_key, SCOPES ); jwtClient.authorize(); const drive = google.drive({ version: "v3", auth: jwtClient });

In the part-1 we have generated key from our service account, from this we will get client email and private key. This key will be in JSON file as shown below.


{ "type": "service_account", "project_id": "oceanic-hold-418705", "private_key_id": "670794b59e1320481635618afab41118b8fc4f19", "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDQVSSDdEsVH5YW\n88hfLUxTlycxxU6xIuWeCNzFlIcOpj8oaR13bckJmkkpHlqson6XlaKQHnQW5BPR\naGmX4K++oIQbqEPkjbeHkHjPV4oZ+v0XosmLXXbdu3EkOvBbl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MTX+6GjIpk/24Tqn9Xxe5ia+HMnWk0DfmjJUB8RahAoGBAIlE\nxfjqk1JrfLSo/3cdDrs26ZrpCcgLiDlZvhLVktMKJR2ySCaI3ojVkB2rnyz9dN1B\nu9G+ojbSk32YzoAf9M1GUwxx3X8X39vsA8khoQZ1THWyhIch8a8uxYgiXs5cxzfb\n0B+gIxv/poqku1YXCbHPWdbTqj7qalB6jKWb9LdNAoGBAOU58VG/p5F68yYAikUS\nFn7BMIOlO+cQ8lVh8AenrRBcpxhDHDLATozzz7bKIJtRsPJOnWpUaX2pBqgxHY8l\nkt59o6rVwL0yhIwQI5VI7Kk74NkFwms7pIEPjABoJ0m1xwmPi+lMEE8gyGwSNqjv\ntpUtpE7TCRHpnXNpn6+VdUvq\n-----END PRIVATE KEY-----\n", "client_email": "demogoogledrive@oceanic-hold-418705.iam.gserviceaccount.com", "client_id": "107363819391282120386", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/demogoogledrive%40oceanic-hold-418705.iam.gserviceaccount.com", "universe_domain": "googleapis.com" }

Let see now how to upload file to folder which we have created in our drive.

Upload files to drive

Set file name and give folder id in which we want to store file. If everything works as expected, you will see the File ID of the uploaded file printed in the console.


try {
    const fileMetadata = {
      name: "my_sales", // Name of the file you want to upload to google drive
      parents: ["1f-1aP8fYFCjDxh4t4atVfe6brDpn0kc0"], // id of the folder in google drive
    };
    const fileResponse = await drive.files.create({
      requestBody: fileMetadata,
      media: {
        mimeType: "application/pdf",
        body: fs.createReadStream(`./src/files/upload/${filename}`), // give path to file where it is located
      },
      fields: "id",
    });
    const updateuserdata = await updateresumedetails(filename, email);
    console.log("File uploaded successfully. File ID:", fileResponse.data.id);
  } 
  catch (error){
    console.error("Error uploading file:", error.message);
  }

Retrive files from drive

const folder_id = "1f-1aP8fYFCHDxh4t4atVde6brDpn0kc0";
  const get = await drive.files.list({
    q: `  '${folder_id}' in parents and name='${resumeid}'`,
    fields: " ",
  });

  await drive.permissions.create({
    fileId: get.data.files[0].id,
    requestBody: {
      role: "reader",
      type: "anyone",
    },
  });
  const returndata = await drive.files.get(
    {
      fileId: get.data.files[0].id,
      alt: "media",
      fields: 'webViewLink , webContentLink'
    }
  );

Conclusion

the provided code snippet demonstrates how to authenticate and authorize access to the Google Drive API using a JWT (JSON Web Token) client in a Node.js environment. By initializing the JWT client with the necessary credentials and scopes, authorizing it to obtain an access token, and then creating a Drive API client with the authorized JWT client, developers cean securely interact with Google Drive services within their applications. This streamlined approach ensures secure access to Google Drive resources while maintaining the flexibility and scalability required for various development scenarios.

references :


Cloud
Bharatsinh Raj
Bharatsinh Raj

Software Engineer

Launch your MVP in 3 months!
arrow curve animation Help me succeed img
Hire Dedicated Developers or Team
arrow curve animation Help me succeed img
Flexible Pricing
arrow curve animation Help me succeed img
Tech Question's?
arrow curve animation
creole stuidos round ring waving Hand
cta

Book a call with our experts

Discussing a project or an idea with us is easy.

client-review
client-review
client-review
client-review
client-review
client-review

tech-smiley Love we get from the world

white heart