API 密钥和发现的 Google 表格功能 [英] API key and discovered Google sheets functions

查看:22
本文介绍了API 密钥和发现的 Google 表格功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是关于在使用 Python 写入 Google 工作表时使用 API 密钥进行身份验证.按照入门示例,我使用网址:

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) 

以这种方式传递 API 密钥似乎有效(它不会抛出任何异常.)之后,我尝试使用 batchUpdate 更新电子表格:

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()

这会引发 401 HTTP 错误:请求缺少必需的身份验证凭据."values().clear() 等其他函数会导致相同的错误.

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

如何将 API 密钥传递给已发现的 Python 函数?

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

推荐答案

我认为您的 service 是正确的.问题是不能使用 API 密钥使用用于使用 POST 和 PUT 方法的 Sheets API.为了使用它们,请使用 OAuth2 的访问令牌.我通过我的经验知道这一点.虽然我当时找过这方面的文件,但一直没找到.对不起.

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.

另一方面,您可以使用 Sheets API for GET 方法使用 API 密钥.例如,您可以通过以下示例使用 API 密钥检索值.为了使用它,请分享电子表格.当电子表格未共享时,返回调用方没有权限".如果未使用 API 密钥,则返回请求缺少有效的 API 密钥".这表示需要 API 密钥.

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.

这篇关于API 密钥和发现的 Google 表格功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆