API key and discovered Google sheets functions

丶灬走出姿态 提交于 2019-12-11 05:20:02

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/48412622/api-key-and-discovered-google-sheets-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!