首页 > 解决方案 > 使用 Python 的 POST 请求 API - 状态码 500

问题描述

我正在用 Python(3.7.4,Windows 10)为 POST 请求(REST API)编写脚本,对象是从另一个数据库检索数据并将其移动到另一个数据库。

from os import getenv
import requests

# header includes login credentials and content type
header = {'access_key': "key", "access_token": getenv("token1"), 'content-type': 'application/json'}

# Body includes table names and other specified data to retrieve
body = {
# table names etc.
}

# Post request and printing of the post request text
post_r = requests.post(url = POST_url, data = body, headers = header)
post_text = post_r.text
print(post_text)

这会抛出一个 HTTP 错误状态代码 500。我应该在代码中进行哪些更改才能正确打印post_text

标签: pythonpython-3.xrestpostpython-requests

解决方案


我想出了解决方案:

post_r = requests.post(url = POST_url, data = body, headers = header)

应该改为

post_r = requests.post(url = POST_url, json = body, headers = header)

所以,我只是用json替换了数据,脚本打印了post_text输出就好了。

将标头中的'content-type'更改为'application'并没有帮助。它向我抛出了状态代码 415(“HTTP 415 Unsupported Media Type client 错误响应代码表明服务器拒绝接受请求,因为有效负载格式的格式不受支持。格式问题可能是由于请求指定的 Content-Type 或Content-Encoding ,或者直接检查数据的结果。”)。

我仍然想知道为什么data = body在发布请求行中是不可接受的。


推荐阅读