首页 > 解决方案 > python中的googleapiclient,使用updateContact返回403

问题描述

我正在尝试从谷歌的 API 获取联系人列表,然后更新其中的一些。在运行该功能时,我每次都会updateContact收到 403 错误。 我正在使用以下代码读取联系人的 etag:Request person.etag is different than the current person.etag. Clear local cache and get the latest person."

service = build('people', 'v1', credentials=creds)
results = service.people().connections().list(
        resourceName='people/me',
        pageSize=100,
        personFields='names,emailAddresses').execute()
connections = results.get('connections', [])

然后对于contact中的每一个,我都在connections尝试更改联系人 givenName 和 familyName:

service.people().updateContact(resourceName="contact's resource name",
                              updatePersonFields="names",
                              body={
                                  "etag": "contact's etag",
                                  "names": [
                                    {
                                      "familyName": "new family name",
                                      "givenName": "new given name"
                                    }
                                  ]
                                }
                              ).execute()

联系人的etagresourceName取自连接的列表响应。
例如:

print(connections[0])
{'resourceName': 'people/<resource_number>',
 'etag': 'etag string',
 'names': [{'metadata': {'primary': True,
    'source': {'type': 'CONTACT', 'id': 'id number'}},
   'displayName': 'x',
   'familyName': 'x',
   'givenName': 'x',
   'displayNameLastFirst': 'x',
   'unstructuredName': 'x'}]}

标签: pythongoogle-api

解决方案


运行您的确切代码确实有效

我运行了您的代码并基于Google People Python Quickstart,同时仅更改了两件事:

  1. 权限

  2. 添加您的代码

    SCOPES = ['https://www.googleapis.com/auth/contacts']
    
    ...
    
    service = build('people', 'v1', credentials=creds)
    
    results = service.people().connections().list(
        resourceName='people/me',
        pageSize=5,
        personFields='names,emailAddresses').execute()
    connections = results.get('connections', [])
    
    for contact in connections:
        service.people().updateContact(resourceName=contact['resourceName'],
                                       updatePersonFields="names",
                                       body={
                                           "etag": contact['etag'],
                                           "names": [
                                               {
                                                   "familyName": "new family name",
                                                   "givenName": "new given name"
                                               }
                                           ]
                                       }
                                       ).execute()
    

推荐阅读