pythonpython-3.xpython-requestshttpresponse

HTTPResponse object has no attribute json


I am retrieving data from an API which outputs some json content. However when I try to store the data into a simple text file with the following code:

import urllib3
import json

http = urllib3.PoolManager()
url = 'http://my/endpoint/url'
myheaders = {'Content-Type':'application/json'}
mydata = {'username':'***','password':'***'}
response  =  http.request('POST', url, body=json.dumps(mydata).encode('UTF-8'), headers=myheaders)
print(response.status_code)
data = response.json()

with open('data.json', 'w') as f:
    json.dump(data, f)

I get the following error :

AttributeError: 'HTTPResponse' object has no attribute 'json'

So, I also tried using response.text with the following code:

file = open('data.json', 'w')
file.write(response.text)
file.close()

But I also get this error:

AttributeError: 'HTTPResponse' object has no attribute 'text'

Why can't I store my response into a simple text file ?


Solution

  • It seems you mix code for module requests with code for module urllib3

    requests has .status_code, .text, .content, .json() but urllib3 doesn't have it

    requests

    import requests
    
    url = 'https://httpbin.org/post'
    
    mydata = {'username': '***', 'password': '***'}
    
    response = requests.post(url, json=mydata)
    print(response.status_code)
    
    data = response.json()
    print(data)
    
    with open('data.json', 'wb') as f:
        f.write(response.content)
        #json.dump(data, f)
    

    urllib3

    import urllib3
    import json
    
    http = urllib3.PoolManager()
    
    url = 'https://httpbin.org/post'
    myheaders = {'Content-Type': 'application/json'}
    mydata = {'username': '***', 'password': '***'}
    
    response = http.request('POST', url, body=json.dumps(mydata).encode('UTF-8'), headers=myheaders)
    #print(dir(response))
    print(response.status)
    
    data = json.loads(response.data)
    print(data)
    
    with open('data.json', 'wb') as f:
        f.write(response.data)