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:

The easiest way to do Web Scraping

Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


Try ProxiesAPI for free

curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

<!doctype html>
<html>
<head>
    <title>Example Domain</title>
    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
...

X

Don't leave just yet!

Enter your email below to claim your free API key: