Curl POST request into pycurl code Curl POST request into pycurl code curl curl

Curl POST request into pycurl code


In your bash example, the property target is an array, in your Python example it is a string.

Try this:

data = json.dumps({"name": "abc", "path": "def", "target": ["ghi"]})

I also strongly advise you to check out the requests library which has a much nicer API:

import requestsdata = {"name": "abc", "path": "def", "target": ["ghi"]}response = requests.post('http://some-url', json=data)print response.status_code


PycURL is a wrapper on the libcurl library written in C language so its Python API can be bit puzzling. As some people are advocating use of python requests instead I just want to point out that it isn't a perfect replacement. For me, its lack of DNS resolution timeout was a deal breaker. I also find it much slower on my Raspberry Pi. This comparison may be relevant:Python Requests vs PyCurl Performance

So here's something that doesn't evade OP's question:

import pycurlimport jsonfrom cStringIO import StringIOcurl = pycurl.Curl()curl.setopt(pycurl.URL, 'http://some-url')curl.setopt(pycurl.HTTPHEADER, ['Accept: application/json',                                'Content-Type: application/json'])curl.setopt(pycurl.POST, 1)# If you want to set a total timeout, say, 3 secondscurl.setopt(pycurl.TIMEOUT_MS, 3000)## depending on whether you want to print details on stdout, uncomment either# curl.setopt(pycurl.VERBOSE, 1) # to print entire request flow## or# curl.setopt(pycurl.WRITEFUNCTION, lambda x: None) # to keep stdout clean# preparing body the way pycurl.READDATA wants it# NOTE: you may reuse curl object setup at this point#  if sending POST repeatedly to the url. It will reuse#  the connection.body_as_dict = {"name": "abc", "path": "def", "target": "ghi"}body_as_json_string = json.dumps(body_as_dict) # dict to jsonbody_as_file_object = StringIO(body_as_json_string)# prepare and send. See also: pycurl.READFUNCTION to pass function insteadcurl.setopt(pycurl.READDATA, body_as_file_object) curl.setopt(pycurl.POSTFIELDSIZE, len(body_as_json_string))curl.perform()# you may want to check HTTP response code, e.g.status_code = curl.getinfo(pycurl.RESPONSE_CODE)if status_code != 200:    print "Aww Snap :( Server returned HTTP status code {}".format(status_code)# don't forget to release connection when finishedcurl.close()

There are some more interesting features worth checking out in the libcurl curleasy setopts documentation


I know this is over a year old now, but please try removing the whitespace in your header value.

c.setopt(pycurl.HTTPHEADER, ['Accept:application/json'])

I also prefer using the requests module as well because the APIs/methods are clean and easy to use.