首页 > 解决方案 > 在python中发布错误请求rest api

问题描述

我正在尝试通过 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 是正确的。为什么它返回“错误请求”状态码?

标签: pythonapirestendpoint

解决方案


我替换datajson它并且它起作用了。

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

我按照 AndroidDev 的建议使用 Postman 来调试它。


推荐阅读