TypeError: 'Response' object is not subscriptable in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
2 min

banner

# TypeError: 'Response' object is not subscriptable in Python

The Python "TypeError: 'Response' object is not subscriptable" occurs when we try to access a key in a Response object without parsing it first.

To solve the error, use the json() method to parse the JSON response to native Python object, e.g. res.json().

typeerror response object is not subscriptable

Here is an example of how the error occurs.

main.py
import requests def make_request(): res = requests.post( 'https://reqres.in/api/users', data={'name': 'Bobby Hadz', 'job': 'manager'}, timeout=10, ) # ⛔️ TypeError: 'Response' object is not subscriptable print(res['name']) make_request()

response object is not subscriptable

The issue in the code sample is that the Response object does not just store the response data.

# Parse the JSON response by calling the json() method

To solve the error, call the json() method on the Response to parse the JSON response object into a native Python object.

main.py
import requests def make_request(): res = requests.post( 'https://reqres.in/api/users', data={'name': 'Bobby Hadz', 'job': 'manager'}, timeout=10 ) # ✅ Parse JSON response to native Python object data = res.json() # 👇️ {'name': 'Bobby Hadz', 'job': 'manager', 'id': '649', 'createdAt': '2022-05-20T10:11:23.939Z'} print(data) print(data['name']) # 👉️ "Bobby Hadz" print(data['job']) # 👉️ "manager" print(data['id']) # 649 make_request()

parse json response by calling json method

We called the json() method on the Response object to parse it into a native Python object before accessing any of its keys.

You should use the json() method to parse the data from all requests, not just HTTP POST.

The "TypeError: object is not subscriptable" means that we are using square brackets to either access a key in a specific object or to access a specific index, however, the object doesn't support this functionality.

To solve the error, convert the object to a dictionary (or list) or another data structure that is subscriptable.

You should only use square brackets to access subscriptable objects.

The subscriptable objects in Python are:

  • list
  • tuple
  • dictionary
  • string

All other objects have to be converted to a subscriptable object by using the list(), tuple(), dict() or str() classes to be able to use bracket notation.

Subscriptable objects implement the __getitem__ method whereas non-subscriptable objects do not.

main.py
a_list = [2, 4, 6, 8] # 👇️ <built-in method __getitem__ of list object at 0x7f71f3252640> print(a_list.__getitem__)
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.