Python调用Google People API返回空列表/无结果问题求助
问题排查与解决方案
你遇到的返回空列表的核心原因和对应修复方法如下:
核心根因
你当前使用服务账号进行身份认证,未配置用户模拟的情况下,people/me指向的是服务账号本身的身份,服务账号默认没有任何联系人数据,因此返回空列表。同时代码存在变量覆盖的逻辑问题,即使请求拿到数据也会出现无法正常输出的情况。
修复步骤
- 如果你使用的是普通个人Gmail账号:普通Gmail不支持服务账号直接访问个人联系人数据,请删除服务账号相关的认证逻辑,改用OAuth 2.0桌面应用授权流程,你的代码中已经导入了相关依赖,直接替换认证逻辑即可。
- 如果你使用的是Google Workspace企业账号:需要先在Google Admin控制台为服务账号开启全域委派权限,创建凭证时新增
subject参数指定你要读取联系人的目标用户邮箱。 - 修正代码中的变量覆盖逻辑:第二次调用
connections.list拿到返回结果后,需要重新获取connections列表再遍历。 - 调整Scope后务必删除本地缓存的旧授权凭证文件,重新发起授权确保权限生效。
修复后代码示例
1. 普通个人Gmail适配版本
import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials # 修改Scope后请删除旧的token.json文件 SCOPES = ['https://www.googleapis.com/auth/contacts.readonly'] def main(): creds = None # 加载本地缓存的授权凭证 if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) # 凭证不存在或过期则重新发起授权 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()) service = build('people', 'v1', credentials=creds) # 调用People API print('List 10 connection names') results = service.people().connections().list( resourceName='people/me', pageSize=10, personFields='names,emailAddresses', fields='connections,totalItems,nextSyncToken' ).execute() connections = results.get('connections', []) print(f"查询到的联系人总数:{results.get('totalItems', 0)}") for person in connections: names = person.get('names', []) if names: name = names[0].get('displayName') print(name) if __name__ == '__main__': main()
使用前请先在Google Cloud控制台创建OAuth 2.0桌面客户端凭证,下载保存为credentials.json放在代码同级目录。
2. Google Workspace服务账号适配版本
from googleapiclient.discovery import build from google.oauth2 import service_account SCOPES = ['https://www.googleapis.com/auth/contacts.readonly'] SERVICE_ACCOUNT_FILE = '<你的服务账号密钥文件路径>.json' # 替换为你要读取联系人的Workspace用户邮箱 TARGET_USER_EMAIL = 'xxx@你的企业域名.com' def main(): credentials = service_account.Credentials.from_service_account_file( SERVICE_ACCOUNT_FILE, scopes=SCOPES, subject=TARGET_USER_EMAIL ) service = build('people', 'v1', credentials=credentials) print('List 10 connection names') results = service.people().connections().list( resourceName='people/me', pageSize=10, personFields='names,emailAddresses', fields='connections,totalItems,nextSyncToken' ).execute() connections = results.get('connections', []) print(f"查询到的联系人总数:{results.get('totalItems', 0)}") for person in connections: names = person.get('names', []) if names: name = names[0].get('displayName') print(name) if __name__ == '__main__': main()
内容的提问来源于stack exchange,提问作者tom
相关产品推荐
相关产品推荐

