kaizenCoder kaizenCoder - 1 year ago 84
Python Question

How to submit post data via urllib2 in python 2.4?

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("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
I get a TypeError;
TypeError: not a valid non-string sequence or mapping object


So the type error was indeed solved by setting the
attribute value to
but it turns out the
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download