Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Drive API: How to create a file in appDataFolder?

I'm reading this documenation: https://developers.google.com/drive/api/v3/appdata

This is my code:

var fileMetadata = {
    'name': 'config.json',
    'parents': ['appDataFolder']
};
var media = {
    mimeType: 'application/json',
    body: '"sample text"'
};
const request = gapi.client.drive.files.create({
    resource: fileMetadata,
    media,
    fields: 'id'
})
request.execute(function (err, file) {
    if (err) {
        // Handle error
        console.error(err);
    } else {
        console.log('Folder Id:', file.id);
    }
})

I get a 403 error: "The user does not have sufficient permissions for this file."

Does not the user have permission to create a file in his appDataFolder? How to create a file in it?

The scope of gapi client is 'https://www.googleapis.com/auth/drive.appdata' and the user accepted it.


2 Answers

I believe the reason for this error is that you are only using the scope to access the appdata folder, but not the scope to create files. Accessing the app data folder and creating files are two different things. According to your code, you are trying to create a file in the appdata folder.

I suggest you to include both scopes:

https://www.googleapis.com/auth/drive.appdata
https://www.googleapis.com/auth/drive.file

If you are not using incremental authorization, make sure to revoke access and reauthorize again.

Reference: https://developers.google.com/drive/api/v3/about-auth#OAuth2Authorizing

like image 168
Morfinismo Avatar answered Oct 29 '25 08:10

Morfinismo


You don't actually need https://www.googleapis.com/auth/drive.file scope to create or delete data inside the appDataFolder. https://www.googleapis.com/auth/drive.appdata scope covers all that.

Try this. Just pass your auth client to the createFile() function.

// Requiring the modular service is much better than requiring the whole GAPI
const GDrive = require('@googleapis/drive');

function createFile(auth) {
    const drive = GDrive.drive({version: 'v3', auth});

    const fileMetadata = {
        'name': 'config.json',
        'parents': ['appDataFolder']
    };
    const media = {
        mimeType: 'application/json',
        body: '{"TEST": "THIS WORKED"}'
    };

    drive.files.create({
        resource: fileMetadata,
        media: media,
        fields: 'id'
    }).then((resp) => {
        console.log('File Id: ', resp.data.id);
    }).catch((error) => {
        console.error('Unable to create the file: ', error);
    });
}
like image 29
m4heshd Avatar answered Oct 29 '25 10:10

m4heshd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!