I am working on a POST request using requests library.
My post requests is working fine if I am using carriage returns in my payload, such as this:
payload = "{\r\n \"name\": \r\n {\r\n \"@action\": \"login\",\r\n \"@appname\": \"app\",\r\n \"@class\": \"login\",\r\n \"@nocookie\": 1,\r\n \"@code\": \"101\",\r\n \"@psw\": \"12345\",\r\n \"@relogin\": \"0\",\r\n \"@username\": \"user123\"\r\n }\r\n}\r\n"
But if I format it to make the payload look pretty the request is not working:
payload = {
'name':
{
'@action': "login",
'@appname': "app",
'@class': "login",
'nocookie': 1,
'@code': "101",
'psw': "12345",
'@relogin': "0",
'@username': "user123"
}
}
I am getting 500 Error using the second payload. First payload works as expected. Any ideas?
Most likely, you just need to create a JSON string from your structure using the function json.dumps
first:
data = json.dumps(payload)
And then use the data
variable instead of your original payload
.
From the documentation for requests
:
For example, the GitHub API v3 accepts JSON-Encoded POST/PATCH data:
>>> import json >>> url = 'https://api.github.com/some/endpoint' >>> payload = {'some': 'data'} >>> r = requests.post(url, data=json.dumps(payload))
Instead of encoding the dict yourself, you can also pass it directly using the json parameter (added in version 2.4.2) and it will be encoded automatically:
>>> url = 'https://api.github.com/some/endpoint' >>> payload = {'some': 'data'} >>> r = requests.post(url, json=payload)
If you have a dictionary, and the API accepts JSON, you can just pass json=payload
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.