简体   繁体   中英

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM