TypeError: 'Response' object has no attribute '__getitem__'

22,581

Solution 1

The response object is not a dictionary, you cannot use indexing on it.

If the API returns a JSON response, you need to use the response.json() method to decode it to a Python object:

data = response.json()
print("respone is: ", data['result'])

Note that you don't have to encode the request JSON data either; you could just use the json argument to the request.post() method here; this also sets the Content-Type header for you:

response = requests.post(url, json=payload, auth=auth)

Last but not least, if the API uses JSONRPC as the protocol, you could use the jsonrpc-requests project to proxy method calls for you:

from jsonrpc_requests import Server

url = "http://public.coindaddy.io:4000/api/"
server = Server(url, auth=('rpc', '1234'))

result = server.get_running_info()

Solution 2

Just change your source code a bit like this :

 response = requests.post(url, json=json.dumps(payload), headers=headers,   auth=auth).json()

 print("respone is: ", response['result'].encode('utf-8'))

It's true that response object alone can't be indexed instead for that purpose you need to return info in json format (in order parse response information ) which you can do so using json() and Here in order to get proper string you must encode it with utf-8 (other wise your output will be something like this -u'LikeThis)

Share:
22,581
cyclopse87
Author by

cyclopse87

Updated on July 22, 2022

Comments

  • cyclopse87
    cyclopse87 almost 2 years

    I am trying to get a value from a response object in a dictionary, but I keep running into this error, am I wrong in thinking you __getitem__ is more commonly used for indexing in classes?

    Here is the code:

    import json
    import requests
    from requests.auth import HTTPBasicAuth
    
    url = "http://public.coindaddy.io:4000/api/"
    headers = {'content-type': 'application/json'}
    auth = HTTPBasicAuth('rpc', '1234')
    
    payload = {
      "method": "get_running_info",
      "params": {},
      "jsonrpc": "2.0",
      "id": 0,
    }
    
    response = requests.post(url, data=json.dumps(payload), headers=headers,   auth=auth)
    
    
    print("respone is: ", response['result'])
    
  • cyclopse87
    cyclopse87 over 8 years
    if i could +2 I would really appreciate this answer mate.
  • badiya
    badiya almost 7 years
    you should also add an explanation like others.
  • Nik
    Nik almost 7 years
    Sure, I encountered this error today, I will add a better explanation later.