I am trying to access a Google sheet using a cloud function and the sheets API in python, but get a 403 permissions error. I have created a service account, exported the key (included in the cloud function zip I am uploading) and have given this service account the API scopes necessary to access sheets (I've tried both https://www.googleapis.com/auth/spreadsheets and https://www.googleapis.com/auth/drive). Here is the code:
import httplib2
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
def main(request):
scope = ['https://www.googleapis.com/auth/spreadsheets','https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secrets.json', scope)
service = build('sheets', 'v4', http=credentials.authorize(httplib2.Http()))
spreadsheet_id = 'id-of-the-google-sheet'
range = 'Sheet1!A:D'
response = service.spreadsheets().values().get(spreadsheetId=spreadsheet_id, range=range).execute()
cols = response.get('values', [])[0]
return cols[0]
requirements.txt:
google-api-python-client
oauth2client
google-auth-httplib2
google-auth
If I explicitly share the Google sheet with the service account, the authentication does work and I can access the sheet data. The question is why doesn't this work by applying the proper API scopes as the Google accounts admin?
client_secrets.json
coming from? The credentials used here should be derived from thecredentials.json
file you get when enabling the Google Sheets API for your project. See developers.google.com/sheets/api/quickstart/python for an example. – Dustin Ingram