简体   繁体   中英

API key and discovered Google sheets functions

This question is about authenticating using an API key when using Python to write to a Google sheet. Following the Getting Started example, I'm "discovering" the API using an URL:

service = discovery.build('sheets', 'v4', discoveryServiceUrl=
    'https://sheets.googleapis.com/$discovery/rest?version=v4',
    developerKey=APIKEY) 

Passing an API key this way seems to work (it throws no exception.) After that, I try to update the spreadsheet with batchUpdate :

service.spreadsheets().batchUpdate(spreadsheetId=SHEETID,
    body={'requests': requests}).execute()

This throws a 401 HTTP error: "Request is missing required authentication credential." Other functions like values().clear() result in the same error.

How can I pass an API key to discovered Python functions?

I think that your service is correct. The problem is that Sheets API for using POST and PUT methods cannot be used using API key. In order to use them, please use access token by OAuth2. I knew this by my experiences. Although I had looked for the document about this at that time, I had not been able to find it. I'm sorry.

On the other hand, you can use Sheets API for GET method using API key. For example, you can retrieve values using API key by the following sample. In order to use this, please share the Spreadsheet. When the Spreadsheet is not shared, "The caller does not have permission" is returned. If API key is not used for this, "The request is missing a valid API key" is returned. This indicates that API key is required.

service = discovery.build('sheets', 'v4', discoveryServiceUrl=
    'https://sheets.googleapis.com/$discovery/rest?version=v4',
    developerKey=APIKEY)
res = service.spreadsheets().values().get(spreadsheetId=SHEETID, range='sheet1!A1:A1').execute()

If this is not useful for you and I misunderstand your question, I'm sorry.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM