pab
pab

Reputation: 21

why does python requests.post accept json for data but not a dictionary

The documentation seems to indicate I can pass 'data=' as a dictionary, but I get an error unless I use json.dumps()

options = {
    "deviceId":["4d51de64-2235-a465-3aee-5ec495b5b250"],
    "serviceName":"software_manager",
    "serviceVersion":"1.0",
    "actionName":"Dump Log Files" }

res = requests.post( req, data=json.dumps(options), auth=cred) 

If I try to pass options as a dictionary it fails.

res = requests.post( req, data=options, auth=cred) 

data=json.dumps(options) # This works
data=options             # this fails

Why? Am I missing something in the docs?

Upvotes: 2

Views: 1872

Answers (1)

wpercy
wpercy

Reputation: 10090

The data parameter of requests.post() either accepts data as form-encoded (if you pass it a dict) or as a raw string (which is why json.dumps(options) works).

In order to pass in a non-encoded dictionary, you should use the json parameter of .post().

Upvotes: 3

Related Questions