d512
d512

Reputation: 34083

Getting 403 from google drive api

I am trying to access google drive using the node client. This will run on a server in a background process without user involvement. In preparation, I have done the following:

I am able to successfully authenticate as the service account and list files inside the directory. However, I am not able to download any of the files. When I try, I apparently get a 403 error. It's kind of buried in the error message but that appears to be the issue. Here is my code:

const fs = require('fs');
const { google } = require('googleapis');
const auth = require('./service-creds.json');

(async () => {
    let jwtClient = new google.auth.JWT(auth.client_email, null,
        auth.private_key, ['https://www.googleapis.com/auth/drive']);

    try {
        const tokens = await jwtClient.authorize();
        let drive = google.drive('v3');

        const res1 = await drive.files.list({
            auth: jwtClient, q: `name = 'MyFolder'`
        });

        const folder = res1.data.files[0];

        const res2 = await drive.files.list({
            auth: jwtClient,
            q: `'${folder.id}' in parents`
        });

        // print out all files under MyFolder
        res2.data.files.forEach(f => console.log(f.name, f.id));

        const dest = fs.createWriteStream('./myfile.csv');
        const file = res2.data.files[0];

        const response = await drive.files.export({
            fileId: file.id,
            mimeType: file.mimeType,
            auth: jwtClient
        }, {
            responseType: 'stream'
        });

        response.data.on('error', err => {
            console.log(err);
        }).on('end', () => {
            console.log('done');
        }).pipe(dest);
    }
    catch (err) {
        console.log('The API returned an error: ', err);
    }
})();

Here is part of the resulting error:

The API returned an error:
... at Gaxios.<anonymous> (/api-test/node_modules/gaxios/build/src/gaxios.js:73:27)

 Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: 
   { body: 
      Gunzip {
        _readableState: [Object],
        readable: true,
        domain: null,
        _events: [Object],
        _eventsCount: 7,
        _maxListeners: undefined,
        _writableState: [Object],
        writable: true,
        allowHalfOpen: true,
        _transformState: [Object],
        bytesRead: 0,
        _opts: [Object],
        _chunkSize: 16384,
        _flushFlag: 2,
        _finishFlushFlag: 2,
        _scheduledFlushFlag: 0,
        _handle: [Object],
        _hadError: false,
        _buffer: <Buffer 00 00 00 00 00 00 00 00 34 00 00 00 00 00 00 00 ... >,
        _offset: 0,
        _level: -1,
        _strategy: 0 },
     disturbed: false,
     error: null },
  [Symbol(Response internals)]: 
   { url: 'https://www.googleapis.com/drive/v3/files/123abc123abc/export?mimeType=text%2Fplain',
     status: 403,
     statusText: 'Forbidden',
     headers: Headers { [Symbol(map)]: [Object] },
     counter: 0 } }

I have not been able to find anything in the error that states why the 403 is being thrown. It appears to be zipped up but I have not been able to successfully unzip any part of it.

Upvotes: 1

Views: 2675

Answers (1)

Tanaike
Tanaike

Reputation: 201378

  • You want to download a file of text/plain from Google Drive.

If my understanding is correct, how about this modification?

Modification points:

  • I think that the reason of your issue is to download the file of the mimeType of text/plain using the files.export method of Drive API.
    • When Google Docs (Spreadsheet, Document, Slides and so on) files are downloaded, you can do it by the files.export method of Drive API.
    • When you want to download the files except for Google Docs, please use the files.get method.
    • When I tried to download the file of text/plain using the files.export method, I could confirm that the same error occurs.

In order to reflect above points, please modify as follows.

Modified script:

From:
const response = await drive.files.export({
    fileId: file.id,
    mimeType: file.mimeType,
    auth: jwtClient
}, {
    responseType: 'stream'
});
To:
const response = await drive.files.get({
    fileId: file.id,
    alt: "media",
    auth: jwtClient
}, {
    responseType: 'stream'
});

Reference:

Upvotes: 2

Related Questions