I have a query to an job board API using Python Requests. It then writes to a table, that is included in a web page. Sometimes the request will return no data(if there are no op
You have a couple of options depending on what the response actually is. I assume, case 3 applies best:
# 1. Test if response body contains sth.
if response.text:
# ...
# 2. Handle error if deserialization fails (because of no text or bad format)
try:
responses = response.json()
# ...
except ValueError:
# no JSON returned
# 3. check that .json() did NOT return an empty dict
if responses:
# ...
# 4. safeguard against malformed data
try:
data = responses[some_key][some_index][...][...]
except (IndexError, KeyError, TypeError):
# data does not have the inner structure you expect
# 5. check if data is actually something useful (truthy in this example)
if data:
# ...
else:
# data is falsy ([], {}, None, 0, '', ...)