简体   繁体   中英

How do I pass JSON data for a post request in Python?

I am trying to execute a cURL command with Python's Requests module but the server keeps returning response code 406 with the message 'Invalid JSON data'. Below is the cURL command as well as the Python code.

cURL

curl --data "userDetails={'userEmail':'jon.snow@example.com','org_id': '3$$4bjnNP','fName': 'Jon','lName': 'Snow','jobTitle': 'Night's Watch', 'language': 'Andal(Westeros)','userAccessView': 'Both','start_date': '30-Jan-2017','end_date': '29-Jan-2018','never_exp': false}" --cacert "C:\Users\cthakor\Desktop\User Creation\security.cer" --cookie "ASessionID='GQa3GTlLGZ8mGNH67CQvTvAz='" https://www.example.com/api/portal/createUser

Python

session_id_cookie = {'ASessionID': 'GQa3GTlLGZ8mGNH67CQvTvAz='}
new_user_data = {"userDetails":{
                            "userEmail" : "jsnow@example.com",
                            "org_id" : "3$$4bjnNP",
                            "fName" : "Jon",
                            "lName" : "Snow",
                            "jobTitle": "Night's Watch",
                            "language" : "Andal(Westeros)",
                            "userAccessView" : "Both",
                            "start_date" : "30-Jan-2017",
                            "end_date" : "29-Jan-2018",
                            "never_exp" : False,
                            }
                        }

r = requests.post("https://www.example.com/api/portal/createUser",
                     data=new_user_data, cookies=session_id_cookie)

The issue might be with 'jobTitle': 'Night's Watch' . Instead use "jobTitle": "Night's Watch" or you can escape the single quote with slash, 'jobTitle': 'Night\\'s Watch'

In requests, pass a dictionary to the data argument, the dictionary of data will automatically be form-encoded when the request is made.

If you need json-encoded data, using

r = requests.post(url, data=json.dumps(new_user_data))

or

r = requests.post(url, json=new_user_data)

Refers to More complicated POST requests

Do the following :

import json final_data = json.dumps(new_user_data )

pass the final_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