【问题标题】:Error "400 Bad request" when sending JSON object to an api using Python使用 Python 将 JSON 对象发送到 api 时出现错误“400 Bad request”
【发布时间】:2017-08-17 19:09:31
【问题描述】:

这是一段sn-p代码:

api_url = {url}
auth_head = {key: value} << my api authentication header
data = {'title':'Python'}  << the valid json object format that the api accepts

这是我尝试过的:

data = json.dumps(data)
json_obj = json.loads(data)
response = requests.post(api_url, headers = auth_head, data = json_obj)
print(response.text)

这是输出:
“400 错误请求”

为了确保 url 和我的 api 令牌密钥有效,我尝试了 GET:

response = requests.get(api_url, headers = auth_head)
print(response.status_code)

输出: “200”

所以 url 和 api 令牌工作正常。我觉得我没有发送 api 想要的正确 json 对象构造

【问题讨论】:

  • json.dumps 后面紧跟json.loads 有什么意义?您只需取回您开始使用的对象。
  • 确实如此。我尝试不使用 json.loads() 并且还需要修改我的标题字典以添加一个键: value 'content-type': 'application/json' 然后它起作用了。谢谢你:)

标签: python json python-requests


【解决方案1】:

您不需要以json 发送数据。只需将数据作为字典发送。它会接受。 requests 会自动将您的字典编码为 json

【讨论】:

  • 谢谢。我试过了。但是,我还需要修改我的标题字典。在那之后它起作用了:)
猜你喜欢
  • 1970-01-01
  • 2012-12-29
  • 2014-08-22
  • 1970-01-01
  • 2011-05-31
  • 2019-06-01
  • 2015-11-16
  • 1970-01-01
  • 2015-06-17
相关资源
最近更新 更多