buffcat
buffcat

Reputation: 295

Python post request returns 500

I am using requests to make a POST request to create a user. The request succeeds with 201 created when I use curl, however fails with a 500 response when I use requests. My curl command is

curl --user administrator:password -H "Content-Type: application/json" https://localhost:8080/midpoint/ws/rest/users -d @user.json -v

And my python script is:

import requests
import json

headers = {
    'Content-Type': 'application/json',
}

with open('user.json') as j:
    data = json.load(j)

response = requests.post('https://localhost:8080/midpoint/ws/rest/users', headers=headers, data=str(data), auth=('Administrator', 'password'))
print(response)

Can anyone see a reason why my python script would be failing? I am at a loss.

Upvotes: 0

Views: 431

Answers (1)

jwodder
jwodder

Reputation: 57450

str(data) returns the Python representation of data, not its JSON representation. These two forms can differ in things like ' vs. ", True vs. true, and None vs. null. To properly JSONify data, call json.dumps() on it:

response = requests.post(..., data=json.dumps(data))

or let requests do the JSONification:

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

or use the JSON as it appears in user.json directly:

with open('user.json') as j:
    data = j.read()

response = requests.post(..., data=data)

Upvotes: 2

Related Questions