使用Python通过Google People API更新联系人多字段遇错求助
解决Google People API多字段更新报错问题
错误根源
你的报错来自service.people().get()请求——该接口必须指定personFields参数来获取所需字段;同时更新接口updateContact需要用updatePersonFields而非personFields来声明要更新的字段范围。
修正后的完整代码
from google.oauth2.credentials import Credentials from google.auth.transport.requests import Request from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build import os SCOPES = ['https://www.googleapis.com/auth/contacts'] def get_credentials(): creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json') if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) with open('token.json', 'w') as token: token.write(creds.to_json()) return creds def update_contacts(contact_id, given_name, family_name, email_address, phone_number): creds = get_credentials() service = build('people', 'v1', credentials=creds) # 直接构造需要更新的字段,无需先获取完整联系人数据 update_body = { 'names': [{'givenName': given_name, 'familyName': family_name}], 'emailAddresses': [{'value': email_address}], 'phoneNumbers': [{'value': phone_number}] } updated_contact = service.people().updateContact( resourceName=contact_id, updatePersonFields='names,emailAddresses,phoneNumbers', # 这里用updatePersonFields body=update_body ).execute() print('Contact updated:', updated_contact) # 示例调用 # contact_id = 'people/c2288946713327522882' # update_contacts(contact_id, "张三", "李四", "zhangsan@example.com", "+8613800138000")
关键修正说明
- 移除冗余的get请求:Google People API的
updateContact接口不需要先获取完整联系人对象,直接传入要修改的字段即可,减少不必要的请求。 - 修正update参数:将
personFields改为updatePersonFields,该参数用于告诉API哪些字段需要被更新。 - 如果确实需要先获取联系人数据(比如保留其他原有字段),则必须给
get请求添加personFields参数,示例如下:
# 若需先获取联系人数据,需添加personFields contact = service.people().get( resourceName=contact_id, personFields='names,emailAddresses,phoneNumbers' ).execute() contact.update(update_body)
内容的提问来源于stack exchange,提问作者nzioker
相关产品推荐
相关产品推荐

