My current understanding is that data
and files
both put data into the body of a POST (requests.post()
) but what is the difference between them? When should one be used over the other, or both? And finally, could an HTTP API require that things be in one or the other, or can it not possibly matter because they are indistinguishable on the receiving end or something?
content : This attribute returns the raw bytes of the response content. text : The text attribute returns the content as a normal UTF-8 encoded Python string. json() : You can use the json() method to get the response content in JSON format.
text is the content of the response in Unicode, and r. content is the content of the response in bytes.
Let me share what I've found, although it would be much appreciated if someone who actually knows what he/she is talking about could elaborate on this (or correct me).
Here's what the requests api docs have to say about these parameters of the request() method:
data -- (optional) Dictionary or list of tuples [(key, value)] (will be form-encoded), bytes, or file-like object to send in the body of the Request.
and
files -- (optional) Dictionary of 'name': file-like-objects (or {'name': file-tuple}) for multipart encoding upload. file-tuple can be a 2-tuple ('filename', fileobj), 3-tuple ('filename', fileobj, 'content_type') or a 4-tuple ('filename', fileobj, 'content_type', custom_headers), where 'content-type' is a string defining the content type of the given file and custom_headers a dict-like object containing additional headers to add for the file.
I guess the data
will be encoded as content-type application/x-www-form-urlencoded
in the http-request, whereas files
will be encoded as multipart/form-data
. The latter also holds if you pass both data and files. This can also be seen by viewing the resulting request.headers
and request.body
. For more information about these content-types and their intended use you could refer to e.g. W3C recommendations.
Some examples are given in the requests QuickStart guide. These probably also give a good indication of the intended use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With