TIMEX TIMEX - 1 year ago 81
HTTP Question

How do I send a POST request as a JSON?

data = {
'ids': [12, 3, 4, 5, 6 , ...]

I want to send a POST request, but one of the fields should be a list of numbers. How can I do that ? (JSON?)

jdi jdi
Answer Source

If your server is expecting the POST request to be json, then you would need to add a header, and also serialize the data for your request...

import json
import urllib2

data = {
        'ids': [12, 3, 4, 5, 6]

req = urllib2.Request('http://example.com/api/posts/create')
req.add_header('Content-Type', 'application/json')

response = urllib2.urlopen(req, json.dumps(data))

If you don't specify the header, it will be the default application/x-www-form-urlencoded type.

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