How to submit post data via urllib2 in python 2.4?

687 Views Asked by At

I am trying to submit a POST request with data in json format to create a user using the Crowd API.

Here is the code snippet:

url = 'http://crowdserver/crowd/rest/usermanagement/1/user'
payload = '{"name": "sampleuser", "password": {"value": "secret"}, "active": true, "first-name": "Sample", "last-name": "User","display-name": "Sample User", "email": "[email protected]"}'
req = urllib2.Request(url, payload)
req.add_header('Content-type','application/json')
req.add_header("Accept", "application/json")
res = urllib2.urlopen(req)
output = resp.read()
print output
print resp.code

I get the following output:

Bad Request
Error code returned is 400

I thought this might perhaps be an encoding issue so replaced payload with:

payload = json.dumps({"name": "sampleuser", "password": {"value": "secret"}, "active": true, "first-name": "Sample", "last-name": "User","display-name": "Sample User", "email": "[email protected]"})

Which returns:

NameError: name 'true' is not defined

So it looks like "active": true is not in an acceptable format.

If I add double quotes such as "active":"true" I get a TypeError; TypeError: not a valid non-string sequence or mapping object

Update

So the type error was indeed solved by setting the active attribute value to True but it turns out the 400 error was returned due to invalid user data, for example missing password or the user already exists read as the user already exists - I find it odd that the error for invalid input and an existing user share the same error code.

1

There are 1 best solutions below

1
Cole On BEST ANSWER

In this line:

payload = '{"name": "sampleuser", "password": {"value": "secret"}, "active": true, "first-name": "Sample", "last-name": "User","display-name": "Sample User", "email": "[email protected]"}'

Change ..., "active": true, ... to ..., "active": True, ...

Python's True/False are case-sensitive.