使用Python调用SendGrid导入联系人API报错,无法获取上传URL及Header
解决SendGrid导入联系人API获取上传URL失败的问题
问题原因
你调用的PUT /marketing/contacts接口是直接批量提交联系人数据的接口,它要求请求体中必须包含contacts字段(至少一条联系人数据),所以只传file_type和field_mappings会触发“至少需要一个联系人”的错误。而你想要获取上传URL和请求头的需求,应该用SendGrid专门的创建联系人导入任务的API接口。
正确解决方案
使用POST /marketing/contacts/imports接口来创建导入任务,这个接口会返回上传文件所需的URL和签名头,具体代码调整如下:
# 假设你已初始化SendGrid客户端 # sg = sendgrid.SendGridAPIClient(api_key=os.environ.get('SENDGRID_API_KEY')) # 请求数据(可按需添加list_ids等参数) data = { "file_type": "csv", "field_mappings": [ "_rf2_T", "_rf0_T", "_rf1_T", "_rf10_T", "w1_T", "w45_T", "w46_T", "w44_T", "w2_D", "w43_T" ], # 可选:指定导入目标联系人列表ID # "list_ids": ["your_target_list_id"] } # 调用正确的API端点 response = sg.client.marketing.contacts.imports.post( request_body=data ) # 输出响应信息 print(response.status_code) print(response.body) print(response.headers)
后续上传文件步骤
拿到返回的上传URL和签名头后,用PUT请求将CSV文件上传到该URL,示例代码(基于requests库):
import requests # 从响应中提取上传所需信息 import_result = response.json() upload_url = import_result["upload_url"] upload_headers = import_result["headers"] # 读取本地CSV文件并上传 with open("your_contacts_file.csv", "rb") as f: upload_response = requests.put(upload_url, headers=upload_headers, data=f) print(upload_response.status_code)
内容的提问来源于stack exchange,提问作者user20597283
相关产品推荐
相关产品推荐

