【发布时间】:2018-06-02 06:18:04
【问题描述】:
我对使用 API 还很陌生,所以请耐心等待。我已经搜索过类似的其他问题,但没有遇到任何可以帮助我解决问题的解决方案。
使用 Postman,我可以使用 JSON 发出 Put 请求,并且效果很好。当我尝试在 Python 中使用相同的 JSON 正文时,我收到此错误:
{'code': 'E.Internal', 'error': 'An internal error has occurred processing your request. Please notify Customer Support for assistance.', 'status': 'error'}
公司的客户支持不是很有帮助,所以我想看看这里是否有人可以帮助我。
这是我的脚本:
url = 'https://website.com/rest/site/' + record_id
json_body = (JSON body here, same one that works in Postman)
head = {'Accept':'application/json', 'Content-Type': 'application/json'}
response = requests.put(url, auth=(username, password), json=json_body, headers=head)
data = response.json()
print(data)
如果我将 requests.put 更改为 requests.get 并在 "auth=(username, password)" 之后删除所有内容,它可以正常工作并返回记录的 json,所以我可以连接到 API,只是不能用 Python 把任何东西放进去。同样,在 Postman 中基本上是同样的事情。
我到底做错了什么,我该如何输入数据?
【问题讨论】:
-
请将您的程序缩减为能够显示错误的最短的完整程序。尝试使用公开的 URL 来重现您的错误(例如,
http://httpbin.org/put)。当我修改您的程序以使用httpbin.org/put并填写json_body行时,我没有收到错误消息。有关为什么以及如何提供可重现测试用例的更多信息,请参阅minimal reproducible example。 -
仅供参考,这是我根据您的代码 sn-p 构建的示例:ideone.com/eerflC
-
好久没用requests了,json body不应该在“data”字段吗?所以“requests.put(url, auth=(username, password), data=json_body, headers=head)”
-
sehafoc 如果您提交它作为答案,我会选择它。那行得通!出于某种原因,我认为它需要是“json =”,而不是“data =”。