如何使用 Google Colab 向 API 发出 Post 请求

How to make a Post request to an API using Google Colab

我需要使用 Google Colab 提出以下 POST 请求:

POST https://http.msging.net/commands HTTP/1.1
Content-Type: application/json 
Authorization: Key YOUR_TOKEN 

{ 
"id": "a456-42665544000-0123e4567-e89b-12d3", 
"to": "postmaster@wa.gw.msging.net", 
"method": "get", 
"uri": "lime://wa.gw.msging.net/accounts/+55115555555" 
}

我试过:

import requests
import re

YOUR_TOKEN = "mytoken"

data = { 
"id": "a456-42665544000-0123e4567-e89b-12d3", 
"to": "postmaster@wa.gw.msging.net", 
"method": "get", 
"uri": "lime://wa.gw.msging.net/accounts/+55115555555" 
}

headers = {
  "Content-Type": "application/json", 
  "Authorization": YOUR_TOKEN 
}
response = requests.post('https://http.msging.net/commands', headers=headers, data=data)

print(response)

为此我得到:

<Response [400]>

我也试过:

import requests
import re

YOUR_TOKEN = "Key cHJvY29ycG9lc3RldGljYWF2YW5jYWRhMTg6cEFBSXFuYTZOR1FFWnpydFltTlo="

data = { 
"id": "a456-42665544000-0123e4567-e89b-12d3", 
"to": "postmaster@wa.gw.msging.net", 
"method": "get", 
"uri": "lime://wa.gw.msging.net/accounts/+55115555555" 
}

headers = {
  "Content-Type": "application/json", 
  "Authorization": YOUR_TOKEN 
}
response = requests.post('https://http.msging.net/commands HTTP/1.1', headers=headers, data=data)

print(response)

为此我得到:

<Response [404]>

如何使用 Google Colab 获取此请求?

Here is the documentation,不提供例子。只是请求。

您收到 400 Bad Request 错误,因为 - 尽管您将 Content-Type header 设置为 application/json - 您没有发送 JSON 编码的数据.

根据 Python 请求 documentation,发送 JSON 数据时,您需要使用 data 参数并传递 JSON 编码字符串,以及手动将 Content-Type header 设置为 application/json:

payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload), headers={"Content-Type": "application/json"})

或者,如果您不想自己编码 dict,请使用 json 参数,Python 请求将自动为您编码,并设置Content-Type header 到 application/json:

r = requests.post(url, json=payload)

您仍然需要将 TOKEN 密钥添加到 Authorization header,就像您已经做的那样。