Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python requests library: data vs json named arguments with requests.post

According to the relevant portion of the requests library documentation, the primary method to pass a dictionary to the post method is as follows:

r = requests.post(url, data = {"example": "request"})

Afterwards, the authors demonstrate an example of passing a JSON string directly to the Github API. Then the authors suggest that instead of encoding the dictionary as a JSON string and passing it via data, you can simply use the named parameter json to pass a dictionary in as follows.

r= requests.post(url, json = {"example": "request"})

When would you use json instead of data? Is this redundancy idiosyncratic or intentional?

like image 544
W4t3randWind Avatar asked Nov 08 '17 19:11

W4t3randWind


1 Answers

Passing a dict to data causes the dict to be form-encoded, as though you were submitting a form on an HTML page; e.g., data={"example": "request"} will be sent in the request body as example=request. The json keyword, on the other hand, encodes its argument as a JSON value instead (and also sets the Content-Type header to application/json).

like image 72
jwodder Avatar answered Oct 23 '22 03:10

jwodder