如何通过API获取同事委派给自己的全部Google Contacts?
获取委派(共享)的Google Contacts指南
Got it, let's break down how to fetch those delegated Google Contacts via the API—here's what you need to know:
1. 前期准备
- 先在Google Cloud Console启用People API:创建新项目,找到People API并开启它。
- 生成OAuth 2.0凭据:选「桌面应用」或「Web应用」类型,下载JSON格式的凭据文件,用来后续做授权验证。
- 申请正确的权限范围:只读需求的话,用
https://www.googleapis.com/auth/contacts.readonly就够;要是需要修改,就用https://www.googleapis.com/auth/contacts。
2. 核心API调用方法
你得用people.connections.list接口来拉取联系人,这个接口会返回当前授权用户的所有联系人,包括同事共享/委派给你的那些。关键是要从结果里筛选出共享来源的联系人:
关键参数说明
resourceName:固定填people/me,代表当前授权的你自己。personFields:指定要获取的字段,必须包含metadata(用来识别共享来源),比如names,emailAddresses,phoneNumbers,metadata。pageSize:设置每页返回的联系人数量,默认100,最大能设到2000。
筛选委派联系人的逻辑
返回的每个Person对象里,检查metadata.sources数组:
- 共享给你的联系人会包含一个
source条目,其中type是CONTACT,且isPrimary为false(说明不是你自己创建的联系人),部分场景下还能看到profileMetadata里标注了共享者的信息。
简单说:只要联系人的来源里有非主来源(不是你自己创建的),那它就是被委派/共享给你的联系人。
3. 示例代码片段(Python)
import google.auth from googleapiclient.discovery import build # 加载OAuth凭据(假设你下载的凭据文件叫credentials.json) creds, _ = google.auth.load_credentials_from_file( 'credentials.json', scopes=['https://www.googleapis.com/auth/contacts.readonly'] ) # 构建People API客户端 service = build('people', 'v1', credentials=creds) # 拉取联系人列表,必须包含metadata字段 results = service.people().connections().list( resourceName='people/me', pageSize=2000, personFields='names,emailAddresses,metadata' ).execute() connections = results.get('connections', []) # 筛选出委派/共享的联系人 delegated_contacts = [] for person in connections: sources = person.get('metadata', {}).get('sources', []) # 检查是否存在非主来源的联系人条目 is_delegated = any(not source.get('isPrimary', True) and source.get('type') == 'CONTACT' for source in sources) if is_delegated: delegated_contacts.append(person) # 输出结果 print(f"找到{len(delegated_contacts)}个委派联系人:") for contact in delegated_contacts: name = contact.get('names', [{}])[0].get('displayName', '未命名') email = contact.get('emailAddresses', [{}])[0].get('value', '无邮箱') print(f"- {name}: {email}")
4. 注意事项
- 如果你在Google Workspace环境里,可能需要管理员先开启相关API权限,确保你能访问共享联系人。
- 第一次授权时,得走OAuth登录流程,给应用授予访问联系人的权限。
- 如果联系人数量超多,记得处理分页逻辑——用返回结果里的
nextPageToken来拉取下一页数据。
内容的提问来源于stack exchange,提问作者Ramaraj Karuppusamy
相关产品推荐
相关产品推荐

