5

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.

8
  • Yes, I just added it in the question. Nothing comes back, its empty Commented Sep 26, 2016 at 15:33
  • After modifying your code to get it to run. I successfully got a response on the following URL. httpbin.org/post I suggest you modify your example code so it is as short as is possible while still presenting this undesired behaviour. Also, make sure that it runs without us needing to do anything, (add the imports, remove joe variable) This might also help you see where the problem is not in. Commented Sep 26, 2016 at 15:45
  • ok, thank you for the advice. Were you able to locate the issue? Commented Sep 26, 2016 at 15:51
  • No, because I wasn't able to reproduce it. Commented Sep 26, 2016 at 15:53
  • Try this code, it is the simplest post request possible minimal reproducible example that works: import requests url="httpbin.org/post" response = requests.post (url, "hi") print(response.text) Commented Sep 26, 2016 at 15:54

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.