Le Ray
Le Ray

Reputation: 387

Convert CURL Post to Python Requests Failing

I am unable to successfully convert and execute a curl post command to python code.

curl command

curl -X POST -H "Content-Type:application/json; charset=UTF-8" -d '{"name":joe, "type":22, "summary":"Test"}' http://url

Converted code

import requests
import json 

url="http://url"
data = {"name":joe, "type":22, "summary":"Test"}
headers = {'Content-type': "application/json; charset=utf8"}
response  = requests.post (url, data=json.dumps(data), headers=headers)
print response.text
print response.headers

I get no response in return, when I execute it manually from the shell it works fine, but when I execute the code, nothing happens, I don't see errors or anything.

Upvotes: 5

Views: 673

Answers (2)

IsaacE
IsaacE

Reputation: 305

In case you have a proxy configured at your environment, define it at your session/request as well.

For example with session:

my_proxies = {  
'http': 'http://myproxy:8080',  
'https': 'https://myproxy:8080'  
}  

session = requests.Session()  
request = requests.Request('POST', 'http://my.domain.com', data=params_template, headers=req_headers, proxies=my_proxies)  
prepped = session.prepare_request(request)  
response = session.send(prepped)  

see documentation:
request http://docs.python-requests.org/en/master/user/quickstart/
session http://docs.python-requests.org/en/master/user/advanced/

Upvotes: 1

suselrd
suselrd

Reputation: 794

If you are using one of the latest versions of requests: Try using the 'json' kwarg (no need to convert to json explicitly) instead of the 'data' kwarg:

response = requests.post(url, json=data, headers=headers)

Note: Also, this way you can omit the 'Content-type' header.

Upvotes: 1

Related Questions