Sendgrid/python - json 无法解组

Sendgrid/python - json could not be unmarshalled

这个python3代码returns一个错误:

import json
import requests

# Perform a Single Send 

headers = {
    "authorization": "Bearer <my-API-key>",
    "content-type": "application/json"
}

data = {
    "name": "Test Blast",
    "send_to": {
        "segment_ids": ["<a-segment-id>"],
        "all": False
    },
    "email_config": {
        "subject": "Test Blast",
        "html_content": "<h1>My Message</h1><p>Is a very simple one.</p>",
        "generate_plain_content": True
    }
}

url = "https://api.sendgrid.com/v3/marketing/singlesends"
res = requests.post(url, headers=headers, data=json.dumps(payload))
print((res.status_code, res.text))

响应是

(400, '{"errors":[{"field":"name","message":"cannot be empty string"}]}')

信息量不大。 运行 与 https://sendgrid.com/docs/api-reference/ 上的 'Try it out' 接口相同的数据(python 布尔值更改为 true/false) 给出

的错误响应
{
    "errors": [
        {
            "field": "",
            "message": "json could not be unmarshalled"
        }
    ]

有什么问题或缺失的线索吗?

这一行有问题:

res = requests.post(url, headers=headers, data=json.dumps(payload))

您在请求中传递了空的负载变量。您已将 json 分配给数据变量并传递有效负载。

因此您需要将变量 payload 更改为此 line.After 中的数据,它将起作用。

res = requests.post(url, headers=headers, data=json.dumps(data))