SuB
SuB

Reputation: 25

Q about scope value when using gspread API to read google sheet with Python

I am new to google apis. I am looking to read a google spreadsheet via a python program and following instructions found here:

https://www.twilio.com/blog/2017/02/an-easy-way-to-read-and-write-to-a-google-spreadsheet-in-python.html

I have a google sheet called Legislators 2017 that I am using for this.

The following is the code to print out some content from the sheet.

import gspread
from oauth2client.service_account import ServiceAccountCredentials


scope = ['https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('google_drive_oct_6_2020.json', scope)
client = gspread.authorize(creds)

sheet = client.open("Legislators 2017").sheet1

list_of_hashes = sheet.get_all_records()
print(list_of_hashes)

The above works.

I am inclined to use the smallest scope possible in general, and would like to use

https://www.googleapis.com/auth/spreadsheets or 
https://www.googleapis.com/auth/spreadsheets.readonly

but they don't work and I get an exception with the following message:

Insufficient Permission: Request had insufficient authentication scopes.

What am I missing ?

Upvotes: 2

Views: 1630

Answers (2)

Tanaike
Tanaike

Reputation: 201338

When client.open("Legislators 2017") is used, the method of "Files: list" in Drive API is used. Ref By this, the scope of Drive API is required to be used. In your script, https://www.googleapis.com/auth/drive or https://www.googleapis.com/auth/drive.readonly are required.

When you don't want to use the scopes of Drive API and want to use the smallest scope possible in general, how about the following modification?

From:

scope = ['https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('google_drive_oct_6_2020.json', scope)
client = gspread.authorize(creds)

sheet = client.open("Legislators 2017").sheet1

To:

scope = ['https://www.googleapis.com/auth/spreadsheets.readonly']
creds = ServiceAccountCredentials.from_json_keyfile_name('google_drive_oct_6_2020.json', scope)
client = gspread.authorize(creds)

sheet = client.open_by_key("###").sheet1
  • ### is the Spreadsheet ID of Legislators 2017.
  • In this modification, the scope of https://www.googleapis.com/auth/spreadsheets.readonly can be used. Also, https://www.googleapis.com/auth/spreadsheets can be used.

References:

Upvotes: 3

Ishan Joshi
Ishan Joshi

Reputation: 525

When creating the Authentication credentials from GCP, you need to state the level of access given to a Authentication Key. You can then access that level of access, or less.

According to the guide you are referring:

Name the service account and grant it a Project Role of Editor.

Upvotes: 0

Related Questions