After going through several posts in the matter of JSON response.content or response.text; I've been incapable of finding a solution to my problem and so I'm turning to you.
To put it simple, I have to define a function that is meant to ascertain whether status.code is correct and, if so, return the values of the headers along with their respective contents. If the status.code isn't valid, then it has to display the error code.
My attempt at this:
import json
import requests
def API(base_url):
response = requests.get(base_url) #Connecting to URL
if response.status_code == 200:#If connection is successful
head = json.dumps((dict(response.headers)), sort_keys=True, indent=3, separators=(',', ': ')) #Head will contain the header values and sort them
cont = json.dumps(str(response.content), sort_keys=True, indent=3, separators=(',', ': ')) #Cont will do the same for content
return head, cont
else:
return response.status_code, response.reason
print(API('http://wikipedia.org'))
print(API('http://google.com/thehearthisflat'))
By doing this, I realized that 'cont' variable isn't being formatted as JSON. In fact, it keeps returning the original values as if it were python code. However, if you ask the function to return only the values of 'head' it displays the JSON format perfectly for the headers.
This fact leads me to question whether I may be using a wrong argument (json.dumps) to have the response.content correctly formatted and sorted.
Could you please help me understand what am I doing wrong here?
Thank you so much in advance!