While using the requests
module, is there any way to print the raw HTTP request?
I don't want just the headers, I want the request line, headers, and content printout. Is it possible to see what ultimately is constructed from HTTP request?
While using the requests
module, is there any way to print the raw HTTP request?
I don't want just the headers, I want the request line, headers, and content printout. Is it possible to see what ultimately is constructed from HTTP request?
I am using requests version 2.18.4 and Python 3
An even better idea is to use the requests_toolbelt library, which can dump out both requests and responses as strings for you to print to the console. It handles all the tricky cases with files and encodings which the above solution does not handle well.
It's as easy as this:
Source: https://toolbelt.readthedocs.org/en/latest/dumputils.html
You can simply install it by typing:
Here is a code, which makes the same, but with response headers:
I spent a lot of time searching for this, so I'm leaving it here, if someone needs.
Note: this answer is outdated. Newer versions of
requests
support getting the request content directly, as AntonioHerraizS's answer documents.It's not possible to get the true raw content of the request out of
requests
, since it only deals with higher level objects, such as headers and method type.requests
usesurllib3
to send requests, buturllib3
also doesn't deal with raw data - it useshttplib
. Here's a representative stack trace of a request:Inside the
httplib
machinery, we can seeHTTPConnection._send_request
indirectly usesHTTPConnection._send_output
, which finally creates the raw request and body (if it exists), and usesHTTPConnection.send
to send them separately.send
finally reaches the socket.Since there's no hooks for doing what you want, as a last resort you can monkey patch
httplib
to get the content. It's a fragile solution, and you may need to adapt it ifhttplib
is changed. If you intend to distribute software using this solution, you may want to consider packaginghttplib
instead of using the system's, which is easy, since it's a pure python module.Alas, without further ado, the solution:
which yields the output:
Since v1.2.3 Requests added the PreparedRequest object. As per the documentation "it contains the exact bytes that will be sent to the server".
One can use this to pretty print a request, like so:
which produces:
Then you can send the actual request with this:
These links are to the latest documentation available, so they might change in content: Advanced - Prepared requests and API - Lower level classes