TypeError: 'Response' object is not subscriptable in Python

avatar

Borislav Hadzhiev

Last updated: Apr 20, 2022

banner

Photo from Unsplash

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': 'John Smith', 'job': 'manager'} ) # ⛔️ TypeError: 'Response' object is not subscriptable print(res['name']) make_request()

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

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': 'John Smith', 'job': 'manager'} ) # ✅ parse JSON response to native Python object data = res.json() # 👇️ {'name': 'John Smith', 'job': 'manager', 'id': '649', 'createdAt': '2022-05-20T10:11:23.939Z'} print(data) print(data['name']) # 👉️ "John Smith" print(data['job']) # 👉️ "manager" print(data['id']) # 649 make_request()

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, we have to 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.