Hrvoje T
Hrvoje T

Reputation: 3913

How to translate curl POST to requests POST in Python?

I have curl command which I need to transfer to requests POST in Python

curl -X POST -H "Content-Type: application/json" -d '{"val1": -1000, "val2": 15, "val3": "20000", "val4": "22"}'
http://some-site:6000?t=1234567890

I tried with:

payload = {'val1': val1, 'val2': val2, 'val3': val3, 'val4': val4}
r = requests.post(url, params=payload)

r.url returns:

 http://some-site:6000?t=1234567890&val1=-1000&val2=15&val3=20000&val4=22

However, I get val1 is not defined response from server. I can see in curl command that val1 and val2 are int type. Can I send with requests ints and strings separately or this is not the reason for this error?

Upvotes: 3

Views: 2897

Answers (1)

nefo_x
nefo_x

Reputation: 3088

Did you try requests.post(url, json=payload)?.. params=payload append query string arguments and json=payload sends JSON as the body + content-type header

import requests
payload = {'val1': 1, 'val2': 2, 'val3': 3, 'val4': 3}
r = requests.post('http://httpbin.org/post', json=payload)
print(r.json())

>>> {u'args': {},
>>>  u'data': u'{"val3": 3, "val2": 2, "val1": 1, "val4": 3}',
>>>  ...

Upvotes: 4

Related Questions