Reputation: 103
I have a Python script that is using the requests module to post JSON to an API. However, I am posting a hash that uses hex. I'm running into an error when I use the following code:
r = requests.post('apiurl.com/do/stuff', json={"key": '0052ccca'})
The response is a 400 error:
{"message": "Could not parse request body into json: Unrecognized token
\'k0052ccca\': was expecting (\'true\', \'false\' or \'null\')\n at
[Source: [B@410c3139; line: 2, column: 23]"}
In this answer the recommendation is to treat the leading zeros as a string, but I'm already doing that and still getting an error.
Upvotes: 0
Views: 645
Reputation: 362627
>>> import requests
>>> response = requests.post('http://httpbin.org/post', json={"key": '0052ccca'})
>>> print(response.text)
{
"args": {},
"data": "{\"key\": \"0052ccca\"}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Content-Length": "19",
"Content-Type": "application/json",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.18.3"
},
"json": {
"key": "0052ccca"
},
"origin": "38.98.147.133",
"url": "http://httpbin.org/post"
}
There is nothing wrong with decoding that json
, as you can see it is encoded correctly by requests:
>>> response.request.body
b'{"key": "0052ccca"}'
So the problem is server side (or your example code is too different from your real code to reveal the real issue).
Upvotes: 4