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
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
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!