How do I send a POST request as JSON using Python?

Keep in mind you can probably accomplish this better with curl. But if you must use Python, this is absolutely the easiest way I’ve found to do this:

# import json module - will only be available for Python 2.7+
import json

# Build a json data structure:
data = {
'username' : 'admin',
'password' : 'admin',
'other' : 'blah',
}

# Creates the request and adding a json header
req = urllib2.Request('http://acme.com/api/posts/create')
req.add_header('Content-Type', 'application/json')

# Getting the response object
response = urllib2.urlopen(req, json.dumps(data))
print response.read()

Remember that your response.read() will be in string format. So you may get a string output that looks like so:

{"output1":"some stuff","output2":"some more stuff"}

So that you can access say ‘output2’ variable directly, you may need to do something like:

print response.read().split(':')[2]

A few extra places to read about:

Advertisements