Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I send `None` as data in a POST request using Python's `requests` library?

It seems that when a key in data has a value of None, the key isn't included by requests.

>>> req = requests.Request('POST', 'http://google.com', data=dict(a=None, b=1))
>>> req.prepare().body
'b=1'

Why is this the case? I was expecting an empty string, or something like json.dumps(d) where None is rendered as null. I'm sure there's a good reason -- just curious about what it is. (One thing I can think of is that maybe there just isn't an encoding of null or None available to the POST request -- is that true?)

Additionally curious -- why does requests silently ignore such data instead of throwing an error?

like image 517
Eli Rose Avatar asked Mar 28 '16 21:03

Eli Rose


Video Answer


1 Answers

Setting a dictionary element to None is how you explicitly say that you don't want that parameter to be sent to the server.

I can't find this mentioned specifically in the requests.Request() documentation, but in Passing Parameters in URLs it says:

Note that any dictionary key whose value is None will not be added to the URL's query string.

Obviously it uses consistent logic for POST requests as well.

If you want to send an empty string, set the dictionary element to an empty string rather than None.

like image 197
Barmar Avatar answered Sep 27 '22 23:09

Barmar