Search code examples
pythongoogle-sheets-apigoogle-authenticationgspread

How to properly connect to Google Spreadsheets API?


I want to connect to the Google Spreadsheets API with Python.

So I do:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope=['https://www.googleapis.com/auth/spreadsheets', 
'https://wwww.googleapis.com/auth/drive']

credentials = ServiceAccountCredentials.from_json_keyfile_name('cred.json', scope)

gc = gspread.authorize(credentials)

wks = gc.open('datatest').Sheet1

print(wks.get_all_records)

But I get this error

HttpAccessTokenRefreshError: invalid_scope: https://www.googleapis.com/auth/spreadsheets is not a valid audience string.

How can I use Google-auth instead of gspread with this data?


Solution

  • you input 4w !!!!

    X 'https://wwww.googleapis.com/auth/drive'

    O 'https://www.googleapis.com/auth/drive'

    import gspread
    from oauth2client.service_account import ServiceAccountCredentials
    
    scope = ['https://www.googleapis.com/auth/drive']
    credentials = ServiceAccountCredentials.from_json_keyfile_name('CredentialsFile.json', scope)
    ss_app = gspread.authorize(credentials=credentials)  # make sure your Google Sheets API is enabled
    sht = ss_app.open('sheet_name_xxxx')  # In your spreadsheet, click the Share button and paste the client email as same as CredentialsFile.json.client_email, and make sure your Google Drive API is enabled
    wks = sht.worksheet('worksheet_name_xxxx')
    print(wks.acell('A1').value)
    

    hope that it helps.