【问题标题】:Convert CURL request to python 3将 CURL 请求转换为 python 3
【发布时间】:2021-01-28 01:57:33
【问题描述】:

我有这个 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"}]}

【问题讨论】:

标签: python curl


【解决方案1】:
  1. 您可以使用 json 代替数据,
requests.post('http://httpbin.org/post', json={"key": "value"})
  1. 您需要转储数据
requests.post(url, data=json.dumps(data), headers=headers)
  1. 还有一个 question 和你一样。

【讨论】:

    【解决方案2】:

    根据他们的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())
    

    【讨论】:

    • 当然,如果它解决了您的问题,请您接受它作为正确答案
    猜你喜欢
    • 1970-01-01
    • 2016-01-30
    • 2020-03-18
    • 2023-04-02
    • 2019-08-17
    • 2021-07-08
    相关资源
    最近更新 更多