【问题标题】:Getting a 400 error when posting a JSON request using Python使用 Python 发布 JSON 请求时出现 400 错误
【发布时间】:2020-06-30 01:33:45
【问题描述】:

我正在尝试使用 Python 发送一个 POST JSON 请求,并且似乎收到 400 错误并出现解析错误。同样的请求在 Postman 中运行良好。我无法理解我做错了什么并感谢任何指针。

有效的邮递员请求正文:

{
          "document":
        {
            "name": "TestWebiDOC_doc",
            "folderId":1112223}
} 

我在使用 Python 时从 REST 服务收到的错误消息:

{"error_code":"400","message":"ParseError at [row,col]:[0,1]\nMessage: A JSONObject text must begin with '{' at character 1 of \"{\\\"document\\\": {\\\"name\\\": \\\"TestWebiDOC_doc\\\", \\\"folderId\\\": \\\"1112223\\\"}}\". "}

下面的 Python 代码发送 JSON 请求 - 无法缩小我做错的范围:

def create_document(token):
    data = {
            'document':
                {
                    'name' : 'TestWebiDOC_doc',
                    'folderId' : '1112223'}
            }
    headers = {'Content-Type' : 'application/json',
               'Accept' : 'application/json',
               'X-SAP-LogonToken' : token}
    path = _url('/documents/')
    response = requests.post(path, json=json.dumps(data), headers=headers)
    print(response.text)
    print('\nURL to create document : {}'.format(path))
    if response.status_code != 200:
        print('\nUnable to create document: {}'.format(response.status_code))
    else:
        document_id = response['success']['id']
        print('\nCreated document with id : {}'.format(document_id))
        return document_id

【问题讨论】:

  • 抱歉,我的意思是输入 POST - 现在更正了。
  • 你可以试试:response = requests.post(path, json=data, headers=headers)
  • 奇怪的是,我之前尝试过,但它失败了,现在它可以工作了......我现在无法解析响应......{“success”:{“message”:“资源已成功创建标识符为 \"6745515\" 的类型 \"Document\"。","id":"6745515"}}
  • 您可以编辑带有响应的问题以及您想从中解析出哪些部分吗?
  • 试试:response.json()['success']['id']

标签: python json rest


【解决方案1】:

您只需将字典本身作为参数传递给requests.post,如下所示:

response = requests.post(path, json=data, headers=headers)

然后要从响应中获取 ID,请执行以下操作:

response.json()['success']['id']

【讨论】:

    猜你喜欢
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-10
    相关资源
    最近更新 更多