Search code examples
pythongoogle-sheets-apiservice-accountsgspread

How to use the scope https://www.googleapis.com/auth/drive.file correctly


I have tried accessing a Google Sheets file in my Google Drive with this code:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)

gc = gspread.authorize(credentials)

wks = gc.open('my_test').sheet1

print(wks.get_all_records())

I have then created a spreadsheet called my_test in my drive and shared it with the email in credentials.json. It then worked. The scope, however, is too broad and I'd like to use

scope = ['https://www.googleapis.com/auth/drive.file']

instead. But if I change the scope, it cannot find the sheet:

File "/home/my_username/.local/lib/python3.6/site-packages/gspread/client.py", line 130, in open
    raise SpreadsheetNotFound
gspread.exceptions.SpreadsheetNotFound

Why is that? How can I change it? I have googled around a lot and for most people sharing or resharing the spreadsheet worked. In my case the problem persists.

I also tried this Error 500 when performing a query with drive.file scope solution of adding a scope for Drive metadata, but that leads to this permissions error, which could be seen as progress (since it finds the file):

gspread.exceptions.APIError: {
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "status": "PERMISSION_DENIED"
  }
}

However, this error persists even after I set the spreadsheet access to 'public'.

Any hints greatly appreciated!

Oh, and I have a more general question: does the Service Account have access to MY entire drive? Or only to everything that was shared with the Service Account? Cause I have only shared one spreadsheet with it, I am a bit confused on how exactly the permissions work here.


Solution

  • auth/drive.file allows operation on an individual files where you have fileId. This scope is designed to work along with Google File Picker API so that you would be able to get those fileId's with file picker and later perform your operations.

    In your situation you don't have fileId thus when you only specify the file name SDK client tries to list the files and doesn't get any results thus it throws 404 error.

    For the part:

    However, this error persists even after I set the spreadsheet access to 'public'.

    It might be the case that this sheet would be accessible with https://www.googleapis.com/auth/spreadsheets.readonly scope.