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:

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!