Fix Python – How do I send a POST request as a JSON?


Asked By – TIMEX

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?)

Now we will see solution for issue: 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 json
import urllib2

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

req = urllib2.Request('')
req.add_header('Content-Type', 'application/json')

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

Python 3.x

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

This question is answered By – jdi

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0