我试图更新我的SendGrid联系人,无法弄清楚为什么我尝试更新我的联系人的自定义字段不工作。我的保留字段(first_name, last_name, email)更新了,但我的自定义字段没有更新。知道为什么吗?
文档在这里:https://sendgrid.api-docs.io/v3.0/contacts/add-or-update-a-contact
try:
headers = {
'authorization': f"Bearer {settings.SENDGRID_API_KEY}",
}
data = {
"list_ids": [
# "Users" list
"7c2...d20"
],
"contacts": [{
"email": user.email,
"first_name": user.first_name,
"last_name": user.last_name,
"custom_fields": {
"educator_role": user.educator_role,
}
}]
}
response = requests.put("https://api.sendgrid.com/v3/marketing/contacts", headers=headers, data=json.dumps(data))
if(response.status_code != 202):
capture_message(f"Could not add user with email {user.email} to Sendgrid.", level="error")
except:
capture_message(f"Adding/updating SendGrid contact failed for {user.email}.", level="error")```
与保留字段不同,更新自定义字段需要在调用中传递自定义字段id
而不是字段name
。因此,使用id代替educator_role
,它将是随机的,如e1_T
。
您可以通过/marketing/field_definitions端点获得id。
正如@Matt所说,要通过SendGrid API更新自定义字段值,我们需要通过其ID引用自定义字段,而不是通过字段名称。
要获取包含自定义字段id的列表,执行:
from sendgrid import SendGridAPIClient
SENDGRID_API_KEY="print-your-key-here"
sg = SendGridAPIClient(SENDGRID_API_KEY)
response = sg.client.marketing.field_definitions.get()
print(response.body)
另外,请查看文档:https://docs.sendgrid.com/api-reference/custom-fields/get-all-field-definitions.
自定义字段ID具有逻辑
对于自定义字段,唯一ID总是以后缀e
开头。后面是一个整数,表示SendGrid平台上自定义字段的创建顺序,例如1, 2, 3
。后跟下划线_
。后面跟着一个代表自定义字段类型的字母:
- N - Number
- T - Text
- D -日期
下面是一个自定义字段ID列表的示例:
{
"custom_fields":[
{"id":"e1_N","name":"number_field_test","field_type":"Number"},
{"id":"e2_T","name":"text_field_test","field_type":"Text"},
{"id":"e3_D","name":"data_field_test","field_type":"Date"}
]
}