Potential newbie question, but it has been bothering me since long time.
In a lot of Python tutorials, I see very similar snippets to post something to a REST API
import json
import requests
url = 'https://api.blabla.com/v1'
token = '1234'
headers = {
'Authorization: f'Bearer {token}',
'Content-Type: 'application/json'
}
body = {
'name': 'Test name'
}
my_response = requests.post(url, headers=headers, data=json.dumps(body)).json()
print(my_response)
The Request documentation says that the data object should receive a dict. In the above, the body is a dict already, so why is there a need to use json.dump
because that essentially makes it a string (whereas documentation says it should be a dictionary).
So why shouldn't it be:
my_response = requests.post(url, headers=headers, data=body).json()
On another note, the official Requests documentation also says we can pass the json parameter and in this example it would be (if we follow the documentation):
my_response = requests.post(url, headers=headers, json=body).json()
But the JSON parameter should be a JSON object, so if we pass the body as such, it means we are passing a dict object to the JSON parameter which is not what the documentation says.
Note:
data=json.dumps(body)
data=body
data
– the body to attach to the request. If a dictionary or list of tuples[(key, value)]
is provided, form-encoding will take place.https://requests.readthedocs.io/en/master/api/#requests.Request
(emphasis mine)
If you pass a dict as data
, it will be form-encoded . If you pass a dict as json
, it will be JSON-serialised. The json
argument is just a convenience shorthand for data=json.dumps(body)
. Why many use the latter instead of the former… who knows.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.