Sending Text Data in a POST Request with Python Requests

Feb 3, 2024 ยท 2 min read

When making POST requests in Python using the requests module, you may need to send plain text data as the request body. Here's a quick guide on how to properly format and send text/plain data with requests.post.

First, import requests and create your text data as a normal string:

import requests

text_data = "This is some plain text data I want to send in the request" 

To send this in the body of a POST request, specify the data parameter and set the headers to indicate text/plain content:

response = requests.post('https://example.com/api', 
                         data=text_data,
                         headers={'Content-Type': 'text/plain'})

This sends the raw string data. Optionally, you can encode the text as bytes for compatibility:

text_bytes = text_data.encode('utf-8')
requests.post(url, data=text_bytes, headers={'Content-Type': 'text/plain;charset=utf-8'})

Note that some APIs may expect the text formatted in a certain way, like JSON. In that case just serialize or format it before passing in.

Also be careful when sending sensitive data like passwords or API keys. Use proper headers and TLS encryption to secure the requests.

To handle the response, access the response object. For example:

print(response.status_code)
print(response.text) 

This prints the status code and response body. You can also get the headers, cookies and more.

In summary, it's easy to pass text content in a POST with Python requests using the data parameter and setting the Content-Type header appropriately. This opens up many possibilities for interfacing with text-based APIs.

Browse by tags:

Browse by language:

Tired of getting blocked while scraping the web?

ProxiesAPI handles headless browsers and rotates proxies for you.
Get access to 1,000 free API credits, no credit card required!