Working with JSON

If we need to send JSON from a client to a server, the simplest way with the Requests module is using the json parameter, specifying a dictionary structure in key-value format.

The main advantage of using this parameter is that it is not necessary to specify 'Content-Type' in the request. In the json response, we can see that it automatically returns this field with the 'application/json' value:

>>> import requests
>>> response = requests.post('http://httpbin.org/post', json={"key": "value"})
>>> response.status_code
200
>>> response.json()
{'args': {},
'data': '{"key": "value"}',
'files': {},
'form': {},
'headers': {'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'close',
'Content-Length': '16',
'Content-Type': 'application/json',
'Host': 'httpbin.org',
'User-Agent': 'python-requests/2.4.3 CPython/3.4.0',
'X-Request-Id': 'xx-xx-xx'},
'json': {'key': 'value'},
'origin': 'x.x.x.x',
'url': 'http://httpbin.org/post'}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset