Python Forum
Empty response to request causing .json() to error - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Empty response to request causing .json() to error (/thread-27907.html)



Empty response to request causing .json() to error - t4keheart - Jun-26-2020

I have a problem with my code in that the response to my API request is occasionally coming back empty, which causes .json() to error out, as it expects a value.

I need to add some checking to my code, but my attempts so far have failed.

My original line was:

response=requests.get(url + id, headers=h, params=p).json()
But I need to add a check to make sure response.content is not empty... so I tried something like this:

    response=requests.get(url + id, headers=h, params=p)
    if response.content == '':
        return
    else:
        response=response.content
        response=json.loads(response)
However, responses containing empty strings continue to make it through!
What am I doing wrong here? How can I check to ensure that if response.content is empty, then do nothing and continue on through the function?


RE: Empty response to request causing .json() to error - bowlofred - Jun-26-2020

Why not just catch the error?

try:
    response = json.loads(response)
except json.decoder.JSONDecodeError:
    response = ""  # or return or whatever you want to do on a failed decode.