我正在使用 Google People API 访问我的联系人。
我在 Google Developers Console 中激活它并创建了一个项目、一个服务帐户(以 ....iam.gserviceaccount.com
结尾)和一个以 JSON 格式存储的身份验证 key .
当我访问联系人时,它似乎使用我的服务帐户地址而不是我的 Google 帐户的联系人,这导致列表为空。
如何让 API 使用我的帐户而不是服务帐户?
这是我目前的代码:
from google.oauth2 import service_account
from googleapiclient.discovery import build
# pip install google-auth google-auth-httplib2 google-api-python-client
SCOPES = ['https://www.googleapis.com/auth/contacts.readonly']
KEY = '~/private.json'
credentials = service_account.Credentials.from_service_account_file(
KEY, scopes=SCOPES)
service = build(
serviceName='people', version='v1', credentials=credentials)
connections = service.people().connections().list(
resourceName='people/me', personFields='names').execute()
print(connections)
# result: {}
最佳答案
服务帐户不是您,服务帐户是虚拟用户,它有自己的谷歌驱动器帐户、谷歌日历和显然是谷歌联系人。您看到空结果集的原因是您没有向服务帐户添加任何联系人。
服务帐户最常用于授予对开发人员拥有的数据的访问权限。例如,您可以获取服务帐户电子邮件地址并在 google drive 上共享您的一个文件夹,然后它将可以访问您 google drive 帐户上的该文件夹。你可以用谷歌日历做同样的事情。
有一些 API 不允许您与其他用户共享您的数据。 Youtube、adwords、博客和谷歌联系人等等。
您不能使用服务帐户访问您的个人 Google 联系人。您最好的选择是使用 oauth2 验证您的应用程序并以这种方式访问它们。
关于 Google Workspace 的注意事项
如果您有一个 google workspace 帐户,则可以将服务帐户配置为代表域中的用户,但只能代表域中的用户。 Perform Google Workspace domain-wide delegation of authority
关于python - 通过服务帐户使用 Google People API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49064826/