If the response is in json you could do something like (python3):
Copyimport json
import requests as reqs
# Make the HTTP request.
response = reqs.get('https://demo.ckan.org/api/3/action/group_list')
# Use the json module to load CKAN's response into a dictionary.
response_dict = json.loads(response.text)
for i in response_dict:
print("key: ", i, "val: ", response_dict[i])
To see everything in the response you can use .__dict__:
Copyprint(response.__dict__)
Edit in May 2024 to add a suggestion on how to address if objects in the response dict is not JSON serializable.
Copyimport json
...
print(json.dumps(response.text, indent=4, sort_keys=True, default=lambda o:'<not serializable>'))
Answer from Jortega on Stack OverflowHow do I read a response from Python Requests? - Stack Overflow
What is the proper way of using python requests, `requests.request("GET",...)` or`requests.get`? - Stack Overflow
Best way to parse get request response into class objects?
How to get the data out of `requests.Response` object in Python? - Stack Overflow
Videos
If the response is in json you could do something like (python3):
Copyimport json
import requests as reqs
# Make the HTTP request.
response = reqs.get('https://demo.ckan.org/api/3/action/group_list')
# Use the json module to load CKAN's response into a dictionary.
response_dict = json.loads(response.text)
for i in response_dict:
print("key: ", i, "val: ", response_dict[i])
To see everything in the response you can use .__dict__:
Copyprint(response.__dict__)
Edit in May 2024 to add a suggestion on how to address if objects in the response dict is not JSON serializable.
Copyimport json
...
print(json.dumps(response.text, indent=4, sort_keys=True, default=lambda o:'<not serializable>'))
If you push, for example image, to some API and want the result address(response) back you could do:
Copyimport requests
url = 'https://uguu.se/api.php?d=upload-tool'
data = {"name": filename}
files = {'file': open(full_file_path, 'rb')}
response = requests.post(url, data=data, files=files)
current_url = response.text
print(response.text)
Hi r/learnpython,
As part of my learning I have been trying to incorporate more object oriented design to my code where appropriate. I am currently writing a script that makes get requests to a service, and to me it seems like the ideal place to use a custom class. Only I am not sure the best way to go about it.
Say I make a get request to a service that returns a list of objects representing people such as {โnameโ: โfooโ, โDOBโ: โ90/09/21โ, โheightโ: 182.1}. Typically I would get and parse the response like so: requests.get(url, params=params, headers=headers).json(). If successful, this object will be a list of dictionaries where each dictionary represents a person. In this case it is safe to assume that each person dictionary will follow the same schema. So to me it makes sense to have a class Person, and rather than have a list of dictionaries, instead have a list of Person objects.
The obvious way to do this it seems is to loop through the json response and convert each dictionary to a Person object. This approach feels a little โclunkyโ to me, so I was wondering if there is a cleaner way to parse a response into a list of class objects? Perhaps a response method similar to json() except you pass the desired class as an argument (I donโt know if such a thing exists)?
Also if you think that my approach of wanting to parse my response straight to class objects is a bad approach I would very much like to hear that too. I struggle to find any documentation on this online, so maybe there is a reason not to do what I am trying to do? Maybe there is a better way to design this? Any feedback is very welcome, it is all part of the learning process.
Thank you,
u/Smart_Peanut_3640
It looks to me from the source code for the ProxyError exception object in Requests like that object should have the request in it. I know you said you think it doesn't, but this shows that it is at least putting a response field in there, even if it were to end up null.
I would have maybe put this in comments, but you can't format code there. This sure seems though like it would give you what you want:
class RequestException(IOError):
"""There was an ambiguous exception that occurred while handling your
request.
"""
def __init__(self, *args, **kwargs):
"""Initialize RequestException with `request` and `response` objects."""
response = kwargs.pop('response', None)
self.response = response
self.request = kwargs.pop('request', None)
if (response is not None and not self.request and
hasattr(response, 'request')):
self.request = self.response.request
super(RequestException, self).__init__(*args, **kwargs)
class ConnectionError(RequestException):
"""A Connection error occurred."""
class ProxyError(ConnectionError):
"""A proxy error occurred."""
So seeing this code, it seems like something like this would work:
try:
...
session.get(url=url, headers=req_headers, verify=False, allow_redirects=True, timeout=30)
...
except ProxyError as ex:
the_response = ex.response
.. do something with the response ..
I think you may be able to use Request's history functionality to access that object, and Request's standard APIs to go from there:
https://2.python-requests.org//en/latest/user/quickstart/#redirection-and-history
By default Requests will perform location redirection for all verbs except HEAD.
We can use the history property of the Response object to track redirection.
The Response.history list contains the Response objects that were created in order to complete the request. The list is sorted from the oldest to the most recent response.
r = requests.get('http://github.com/')
r.url 'https://github.com/'
r.status_code 200
r.history [<Response [301]>]
Will headers then not give you what you need?
https://2.python-requests.org//en/latest/user/advanced/#advanced
>>> r.headers
{'content-length': '56170', 'x-content-type-options': 'nosniff', 'x-cache':
'HIT from cp1006.eqiad.wmnet, MISS from cp1010.eqiad.wmnet', 'content-encoding':
'gzip', 'age': '3080', 'content-language': 'en', 'vary': 'Accept-Encoding,Cookie',
'server': 'Apache', 'last-modified': 'Wed, 13 Jun 2012 01:33:50 GMT',
'connection': 'close', 'cache-control': 'private, s-maxage=0, max-age=0,
must-revalidate', 'date': 'Thu, 14 Jun 2012 12:59:39 GMT', 'content-type':
'text/html; charset=UTF-8', 'x-cache-lookup': 'HIT from cp1006.eqiad.wmnet:3128,
MISS from cp1010.eqiad.wmnet:80'}
ยป pip install requests