Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy does HTTP POST request body need to be JSON enconded in Python?
    primarykey
    data
    text
    <p>I ran into this issue when playing around with an external API. I was sending my body data as a dictionary straight into the request and was getting 400 errors:</p> <pre><code>data = { "someParamRange": { "to": 1000, "from": 100 }, "anotherParamRange": { "to": True, "from": False } } </code></pre> <p>When I added a json.dumps wrap, it works:</p> <pre><code>data = json.dumps({ "someParamRange": { "to": 1000, "from": 100 }, "anotherParamRange": { "to": True, "from": False } }) </code></pre> <p>I don't entirely understand why this is necessary, as dictionaries and JSON objects are syntactically identical. Can someone help me understand what is going on behind the scenes here?</p> <p>For completeness, here are my headers:</p> <pre><code>headers = {'API-KEY': 'blerg', 'Accept-Encoding': 'UTF-8', 'Content-Type': 'application/json', 'Accept': '*/*', 'username': 'user', 'password': 'pwd'} </code></pre> <p>EDIT:</p> <p>I didn't mention this earlier but now I feel that it may be relevant. I am using the Python Requests library, and another post seems to suggest that you should never have to encode parameters to a request object: <a href="https://stackoverflow.com/a/14804320/1012040">https://stackoverflow.com/a/14804320/1012040</a></p> <p>"Regardless of whether GET/POST you never have to encode parameters again, it simply takes a dictionary as an argument and is good to go."</p> <p>Seems like serialization shouldn't be necessary?</p> <p>My request object:</p> <pre><code>response = requests.post(url, data=data, headers=headers) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload