When working with the popular Python Requests library for making HTTP requests, you may occasionally see this error:
"a bytes-like object is required, not 'str'"
This error occurs when Requests is expecting a
Passing a String as File Data
If you are trying to upload a file using Requests, you need to pass file data as bytes:
with open('data.bin', 'rb') as f:
files = {'file': f}
r = requests.post(url, files=files)
Note the
Passing Encoded Text as the Request Body
When sending text data like JSON in the request body, you need to first encode it to bytes:
data = json.dumps(some_dict)
r = requests.post(url, data=data.encode('utf-8'))
The
Forgetting to Decode Response Content
If you try to access the response
r = requests.get(url)
print(r.text) # may cause bytes-like object error
print(r.content.decode('utf-8')) # decode first
So remember to decode the raw response bytes to a string first.
Summary
Following these tips will help avoid the confusing "bytes-like object required" errors when using Requests.