Curl POST request to pycurl code

I am trying to convert the following curl request to pycurl:

curl -v -H Accept:application/json \ -H Content-Type:application/json \ -d "{ name: 'abc', path: 'def', target: [ 'ghi' ] }" \ -X POST http://some-url 

I have python code:

 import pycurl, json c = pycurl.Curl() c.setopt(pycurl.URL, 'http://some-url') c.setopt(pycurl.HTTPHEADER, ['Accept: application/json']) data = json.dumps({"name": "abc", "path": "def", "target": "ghi"}) c.setopt(pycurl.POST, 1) c.setopt(pycurl.POSTFIELDS, data) c.setopt(pycurl.VERBOSE, 1) c.perform() print curl_agent.getinfo(pycurl.RESPONSE_CODE) c.close() 

While doing this, I got error 415: Unsupported media type, so I changed:

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

in

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

This time I have a 400: Bad request. But bash code with curl works. Do you know what I should fix in python code?

+5
source share
3 answers

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

Try the following:

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

I also strongly recommend that you familiarize yourself with the requests library, which has a much more convenient interface:

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

I know this has been over a year, but please try to remove the spaces in your header value.

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

I also prefer to use the query module because the API / methods are clean and easy to use.

+2
source

Better just use a query library. ( http://docs.python-requests.org/en/latest )

I am adding python code for your original custom curl headers.

 import json import requests url = 'http://some-url' headers = {'Content-Type': "application/json; charset=xxxe", 'Accept': "application/json"} data = {"name": "abc", "path": "def", "target": ["ghi"]} res = requests.post(url, json=data, headers=headers) print (res.status_code) print (res.raise_for_status()) 
-3
source

All Articles