使用Python发布JSON请求时出现400错误

时间:2020-03-18 22:24:17

标签: python json rest

我正在尝试使用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

1 个答案:

答案 0 :(得分:1)

您只需要将字典本身作为参数传递给requests.post,就像这样:

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

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

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