'How to curl in Python with header, data?
I'm trying replace the following curl command by a Python script:
curl --request POST \
--url https://xx.com/login \
--header 'Content-Type: application/json' \
--data '{
"email": "[email protected]",
"password": "PASSWORD"
}'
Script that I tried:
import urllib.request
import json
body = {"email": "[email protected]","password": "xxx"}
myurl = "https://xx.com/login"
req = urllib.request.Request(myurl)
req.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = json.dumps(body)
jsondataasbytes = jsondata.encode('utf-8') # needs to be bytes
req.add_header('Content-Length', len(jsondataasbytes))
response = urllib.request.urlopen(req, jsondataasbytes)
When I tried to run this script, it doesn't return me anything and show processed completed. Is my code logic correct? Or there is something wrong with my code?
Solution 1:[1]
you can simply just use requests:
import requests
headers = {
'Content-Type': 'application/json',
}
data = '{\n"email": "[email protected]",\n"password": "PASSWORD"\n}'
response = requests.post('https://xx.com/login', headers=headers, data=data)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tal Folkman |
