Prashanth
Prashanth

Reputation: 1398

Getting a 400 error when posting a JSON request using Python

I am trying to send a POST JSON request using Python and seem to be getting a 400 error with a parsing error. This same request works fine in Postman..I am unable to understand what I am doing wrong and appreciate any pointers.

Postman request body that works:

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

Error message that I am getting from the REST Service when using Python:

{"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 Code Below to send the JSON request - not able to narrow down what I am doing wrong:

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

Upvotes: 1

Views: 2730

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169484

You would just need to pass the dictionary itself as an argument to requests.post, like this:

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

Then to get the ID from the response, do:

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

Upvotes: 2

Related Questions