The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Dreaming in Puzzles

--

Chapters
00:00 Why Can'T I Send `None` As Data In A Post Request Using Python'S `Requests` Library?
00:42 Accepted Answer Score 15
01:17 Answer 2 Score 3
01:29 Answer 3 Score 6
01:57 Answer 4 Score 0
02:06 Thank you

--

Full question
https://stackoverflow.com/questions/3627...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #httppost #pythonrequests

#avk47



ACCEPTED ANSWER

Score 15


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.




ANSWER 2

Score 6


I had similar issue with a blank value and this was my workaround. I sent the data as json string and set content type headers as application/json. This seems to send the whole data across as expected. Took quite some time to figure out. Hope this helps someone.

import requests
import json

header = {"Content-Type":"application/json"}

data = {
    "xxx": None,
    "yyy": "http://",
    "zzz": 12345
    }

res = requests.post('https://httpbin.org/post', 
                    data=json.dumps(data), headers=header)

obj = json.loads(res.text)

print obj['json']



ANSWER 3

Score 3


I had the same question few days ago and if you replace data with json it should work for you, as now None will be sent in the body.

request('POST', 'http://google.com', json=dict(a=None, b=1))



ANSWER 4

Score 0


The best way is to use parameter json instead of data. If you use :

requests.Request('POST', 'http://google.com', json=dict(a=None, b=1))

It works well