How do I send a POST request as a JSON? How do I send a POST request as a JSON? python python

How do I send a POST request as a JSON?


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...

Python 2.x

import jsonimport urllib2data = {        '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))

Python 3.x

https://stackoverflow.com/a/26876308/496445


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


I recommend using the incredible requests module.

http://docs.python-requests.org/en/v0.10.7/user/quickstart/#custom-headers

url = 'https://api.github.com/some/endpoint'payload = {'some': 'data'}headers = {'content-type': 'application/json'}response = requests.post(url, data=json.dumps(payload), headers=headers)


for python 3.4.2 I found the following will work:

import urllib.requestimport jsonbody = {'ids': [12, 14, 50]}myurl = "http://www.testmycode.com"req = urllib.request.Request(myurl)req.add_header('Content-Type', 'application/json; charset=utf-8')jsondata = json.dumps(body)jsondataasbytes = jsondata.encode('utf-8')   # needs to be bytesreq.add_header('Content-Length', len(jsondataasbytes))response = urllib.request.urlopen(req, jsondataasbytes)