GI D
GI D

Reputation: 65

Python JSON request body construction

I'm having a headache trying to construct a JSON body for a POST request. When the body is fixed and defined like this:

body_works = {"databaseName": "admin",  "username": "foo", "password" : "bar",  "roles": [{"databaseName": "foo-db", "roleName": "readWrite"}]}

...the request below works fine:

response = requests.post(url, auth=auth, headers=headers, json = body_works)

The problem comes up in the non-trivial case where the "username" and "password" parameters inside the body are string variables.

How must I construct the body then?

I have tried this, using single quotes to enclose double quotes:

body = '{"databaseName": "admin",  "username": "' +  username + '", "password": "' + password + '",  "roles": [{"databaseName": "' + username +'", "roleName": "readWrite"}]}'

When I print(%s) the body_works variable above, it prints with single quotes. When I print the body I construct, it prints with double quotes, and the request fails.

Upvotes: 0

Views: 1037

Answers (1)

matszwecja
matszwecja

Reputation: 7970

You need to differentiate between JSON string and Python dicts. What you provided in the first line is a Python dict, while requests expects a json. First example works, because it just so happens that it doesn't use anything that sets those 2 formats apart. As soon as you introduce variables, it becomes clear we're dealing with a Python dict. You can convert it using json.dumps() (inverse operation is json.loads())

import requests, json

body_works = {"databaseName": "admin",  "username": username, "password" : password,  "roles": [{"databaseName": username, "roleName": "readWrite"}]}
response = requests.post(url, auth=auth, headers=headers, json = json.dumps(body_works))

Upvotes: 1

Related Questions