Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 826
colla Avatar asked May 09 '26 20:05

colla


1 Answers

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)
like image 57
furas Avatar answered May 11 '26 10:05

furas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!