I am trying to hit an API endpoint using python requests. I have been unable to successfully send the body of the request except when using cURL. Here is the cURL command that succeeds:
curl --location --request POST '<api endpoint url>' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'obj={"login":"<email>","pword":"<password>"}'
Using python requests like this returns an error from the API because of the body of the request:
payload = 'obj={"login":"<email>","pword":"<password>"}'
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.post(url, headers=headers, data=payload)
print(response.text)
I also tried requests.request("POST") but got the same results.
Your data is URL encoded as you can see in the curl Content-Type header, so you have to provide the data in an URL encoded format, not JSON.
Use the following instead. requests will set the Content-Type header to application/x-www-form-urlencoded automatically. It will also take care of the URL encoding.
data = {"login": "<email>", "pword": "<password>"}
response = requests.post(url, data=data)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With