TypeError: 'Response' object is not subscriptable in Python

avatar

Borislav Hadzhiev

Wed Apr 20 20222 min read

banner

Photo by Melissa Brown

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.

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