'What package and function to use to get a response that can be formatted in JSON after sending a query string

I am currently using AWS Lambda which does not support the "requests" package. Hence I am trying to look for alternatives using urllib3

My code using the "requests" package is as such:

site_dict = {
'1':'JSDOKAJDISADK',
'2':'IOASJD8917238ASDW',
'3':'UIO2NKDNAK123'
for sId in site_dict:
params = {
    'api_key': site_dict[sId]
}
r = requests.get(url = id_url, params = params)
data = r.json()

Params is a dictionary where the Using urllib3:

http = urllib3.PoolManager()
r = http.request('GET', url=id_url, headers=params)
data = r.json()

However, I get the error:

Traceback (most recent call last):
  File "C:\Users\Owner\PycharmProjects\pythonProject\API Test.py", line 37, in <module>
    data = r.json()
AttributeError: 'HTTPResponse' object has no attribute 'json'

How do I get my data which I can then format into JSON format using urllib3?



Solution 1:[1]

Use r.data instead of r.json()

...
data = r.data # and not r.json()

If you want to get Json content you have to use python json module

JSON Content

JSON content can be loaded by decoding and deserializing the data attribute of the request:

import json
import urllib3

http = urllib3.PoolManager()

r = http.request('GET', 'http://httpbin.org/ip')

json.loads(r.data.decode('utf-8'))
{'origin': '127.0.0.1'}

For more info read the official documentation.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1