TypeError: byte indices must be integers or slices, not str

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

TypeError: byte indices must be integers or slices, not str #

The Python "TypeError: byte indices must be integers or slices, not str" occurs when we use a string to access a bytes object at a specific index. To solve the error, use the res.json() method to parse the json response before accessing a specific key.

typeerror byte indices must be integers or slices not str

Here is an example of how the error occurs.

main.py
import requests def make_request(): res = requests.get('https://reqres.in/api/users') for entry in res: # ⛔️ TypeError: byte indices must be integers or slices, not str print(entry['some_key']) make_request()

We forgot to parse the response object into a native Python object.

You can use the res.json() method to do that.

main.py
import requests def make_request(): res = requests.get('https://reqres.in/api/users') # ✅ parse to native Python object parsed = res.json() print(type(parsed)) for entry in parsed: print(entry) make_request()

The error is caused when we use a string to access a bytes object at a specific index.

When we iterate over the response object, we get access to bytes objects (not dictionaries).

Once we parse the response into a native Python object, we can access specific keys in a dictionary.

Here is a very simple example of how the error occurs.

main.py
my_bytes = b'hello world' # ⛔️ TypeError: byte indices must be integers or slices, not str my_bytes['test']

We can use integers or slices as byte indices, but what you most likely need is to parse the object into a native Python object (e.g. a dictionary).

If you aren't sure what type of object a variable stores, use the type() class.

main.py
my_bytes = b'hello world' print(type(my_bytes)) # 👉️ <class 'bytes'> print(isinstance(my_bytes, bytes)) # 👉️ True

The type class returns the type of an object.

The isinstance function returns True if the passed in object is an instance or a subclass of the passed in class.

Use the search field on my Home Page to filter through my more than 1,000 articles.