Python Forum

Full Version: Empty response to request causing .json() to error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
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.