【问题标题】:Post Bad Request rest api in python在python中发布错误请求rest api
【发布时间】:2021-03-31 16:39:44
【问题描述】:

我正在尝试通过 Python 中的 REST API 发布一些数据。

数据.json

    {
      "LastModifiedAt": "2020-12-21T20:19:45.335Z",
       ...
       ...
    }

我正在使用以下代码发布数据。

with open('data.json') as fh:
    data = json.load(fh)
headers = {
    'Content-Type': 'application/json',
    'X-API-Key':'ABC=='
}
response = requests.post('https://myurl.net/api/v1/resource/int_key/endpoint', headers=headers,data=data)

我总是得到以下回复 status_code = 400

{
    "ModelState": {
        "line": [
            "Unexpected character encountered while parsing value: L. Path '', line 0, position 0."
        ]
    }, 
    "Message": "The request is invalid."
}

我该如何调试呢?根据 API 文档,我的 URL 是正确的。为什么会返回“Bad Request”状态码?

【问题讨论】:

  • 我敢打赌,标头和 API 连接有问题,而不是 python。
  • 你是否有权访问后端的反序列化代码。你能发布你的整个 JSON 吗?它几乎肯定是格式不正确的属性之一。如果反序列化器未设置为识别格式,则传递日期尤其棘手。另外,请尝试使用 Postman 发送。

标签: python api rest endpoint


【解决方案1】:

我用json 替换了data,它成功了。

response = requests.post('https://myurl.net/api/v1/resource/int_key/endpoint', headers=headers,json=data)

我按照 AndroidDev 的建议使用 Postman 进行调试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    • 2021-11-16
    • 2020-02-16
    • 1970-01-01
    相关资源
    最近更新 更多