'Python requests application/x-www-form-urlencoded non json body
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.
Solution 1:[1]
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)
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 | Mushroomator |
