Sending String Data in Request Body with Python Requests

Feb 3, 2024 ยท 2 min read

When making HTTP requests in Python using the requests library, you may need to send textual data in the request body. For example, when making PUT requests to create or update a resource on the server.

Here is how to send a string in the request body with Python requests:

Convert String to bytes

The data parameter in requests expects the body to be passed as bytes. So you need to encode the string to bytes before passing it.

import requests

data = "this is a test string"
data = data.encode('utf-8')

Encoding the string to bytes using UTF-8 is generally recommended.

Set Content-Type Header

You should also set the Content-Type header to indicate the data is a string:

headers = {'Content-Type': 'text/plain; charset=utf-8'}

This tells the server to interpret the incoming data as a plain text string encoded with UTF-8.

Make PUT Request

Now you can make the PUT request and pass the encoded string data:

response = requests.put(url, data=data, headers=headers)

The full code would look like:

import requests

url = "http://api.example.com/items/123" 

data = "this is a test string"
data = data.encode('utf-8') 

headers = {'Content-Type': 'text/plain; charset=utf-8'}

response = requests.put(url, data=data, headers=headers)

This sends a PUT request to update or create the resource at the given URL, with the string data in the body.

The server will receive the textual data and process it appropriately based on the resource. For example, saving it to a file or database.

And that's the essential process for sending string data in the body with Python requests!

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: