将 CURL 请求转换为 python 3

时间:2021-01-28 01:57:33

标签: python curl

我有这个 curl 请求,我想转换为 python 3

curl -X "POST" "https://conversations.messagebird.com/v1/send" \\
-H "Authorization: AccessKey YOUR-API-KEY" \\
-H "Content-Type: application/json" \\
--data '{ "to":"+31XXXXXXXXX", "from":"WHATSAPP-CHANNEL-ID", "type":"text", "content":{ "text":"Hello!" }, "reportUrl":"https://example.com/reports" }'

有人可以帮我吗?

我尝试了以下请求,但没有成功:

import requests

header = {"Authorization":"AccessKey YOUR-API-KEY"}
data = { "to":"+31XXXXXXXXX", "from":"WHATSAPP-CHANNEL-ID", "type":"text", "content":{"text":"Hello!" },  "reportUrl":"https://example.com/reports"}
url = 'https://conversations.messagebird.com/v1/send'
response = requests.post(url, data=data, headers=header)
print(response.text)

我收到错误消息:

<Response [400]>
{"errors":[{"code":21,"description":"JSON is not a valid format"}]}

2 个答案:

答案 0 :(得分:0)

  1. 您可以使用 json 代替数据,
requests.post('http://httpbin.org/post', json={"key": "value"})
  1. 您需要转储数据
requests.post(url, data=json.dumps(data), headers=headers)
  1. thers 是另一个像你一样的 question

答案 1 :(得分:0)

根据他们的 documentation,cURL 是正确的,并且将在 Python 中实现:

import requests

header = {
    "Authorization": "AccessKey YOUR-API-KEY", 
    "Content-Type": "application/json"
}
data = {
    "to": "+31XXXXXXXXX", 
    "from": "WHATSAPP-CHANNEL-ID", 
    "type": "text", 
    "content": {"text":"Hello!"}, 
    "reportUrl": "https://example.com/reports"
}
url = 'https://conversations.messagebird.com/v1/send'
response = requests.post(url, json=data, headers=header)

print(response.json())