The Python Requests library makes sending HTTP requests simple. But once you've sent a request, how can you see exactly what data was transmitted? There are a couple handy methods on request objects that let you inspect both the request headers and body that were sent.
Accessing Request Headers
After making a request, the
import requests
resp = requests.get('https://example.com')
print(resp.request.headers)
This includes things like
Viewing Request Body Data
For requests that send data in the body, like POST, you can access it with
data = {'key': 'value'}
resp = requests.post('https://api.example.com', data=data)
print(resp.request.body)
# b'key=value'
However, this will show the urlencoded data, which may not be very readable. To get a nice string, you can set the
import json
data = {'key': 'value'}
resp = requests.post('https://api.example.com', json=data)
print(resp.request.body)
# {"key": "value"}
Now the printed body contains the JSON string that was sent in the request.
Summary
Inspecting the request headers and body can be helpful in debugging issues with APIs or just to confirm what data your Python code is transmitting. The Requests library makes it straightforward to see all aspects of HTTP requests.