Samith Basnayaka
Samith Basnayaka

Reputation: 137

Nodejs Google Drive API Shareable link

For my Nodejs project I'm using Google drive API for file sharing. But the problem is, the URL I'm getting from API is not a shareable link. So I have to go to the drive and switch on the sharing. Is there a way to get the shareable link or switch on the sharing with the java script code? Please give me a solution for this.

Upvotes: 0

Views: 2172

Answers (1)

cutiko
cutiko

Reputation: 10507

The comments were very helpful indeed, this solution is for the v3 of Google Drive and the Google Doc v1. I was using jwt auth for Service Account and the alternativeLink using Drive v2 is not sharable.

I'm assuming the auth process is known and complete. I'm writing the code in blocks so using await, promises, or callbacks is reader choice

First, you need to create a document:

google.docs({version: 'v1', auth});
docs.documents.create({title: "Your Title"}, (error, response) => {
    if (error) return;
    //So now you have the documentId
    const {data: {documentId}} = response;
});

Now with the documentId we need to add a permission to the doc. The key is to grant permission to anyone. The doc explains anyone doesn't need an email or a user.

const resource = {"role": "reader", "type": "anyone"};
drive.permissions.create({fileId:documentId, resource: resource}, (error, result)=>{
    if (error) return;
    //If this work then we know the permission for public share has been created 
});

Now we are almost ready, we only need the URL. Gladly the sharable URL has a stable format, so we can compose it by our selves without the need for an extra request:

https://docs.google.com/document/d/${documentId}}/view

Node.js Google Api changes quickly, in case of any confusion, I'm using "googleapis": "^38.0.0",

Upvotes: 4

Related Questions