Last updated: Apr 8, 2024
Reading time·2 min
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()
.
Here is an example of how the error occurs.
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()
The issue in the code sample is that the Response
object does not just store
the response data.
json()
methodTo solve the error, call the json()
method on the Response
to parse the JSON
response object into a native Python object.
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()
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
.
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:
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.
a_list = [2, 4, 6, 8] # 👇️ <built-in method __getitem__ of list object at 0x7f71f3252640> print(a_list.__getitem__)