Ad

How Should I Pass Text/plain Data To Python's Requests.post?

- 1 answer

I am trying to convert this curl command in python requests, but I am unsure about how I should pass the data:

curl -X POST -u "apikey:{apikey}" \
    --header "Content-Type: text/plain" \
    --data "some plain text data" \
    "{url}"

I have tried to pass the string directly and to encode it with str.encode('utf-8') but I get an error 415 Unsupported Media Type

This is my code:

text = "some random text"
resp = requests.post(url, data=text, headers={'Content-Type': 'text/plain'}, auth=('apikey', self.apikey))

[EDIT]: Solution is not to specify the headers in the request

Thanks a lot!

Ad

Answer

When using requests library, it is usually a good idea not to set Content-Type header manually using headers= keyword.

requests will set this header for you if it is needed (for example posting JSON will always result in Content-Type: application/json header).

Another reason for not setting this type of header manually is encoding, because sometimes you should specify something like Content-Type: text/plain; charset=utf-8.

One more important thing about Content-Type is that this header is not required for making POST requests. RFC 2616:

Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream".

So depending on the server type you're making request to, this header may be left empty.


Sorry for this explanation being a bit vague. I cannot give you an exact explanation why this approach worked for you unless you provide target URL.

Ad
source: stackoverflow.com
Ad