I am making API Calls and expect to get some null responses or NoneTypes. However I am trying to handle them gracefully.
This is the default behavior:
res = req.json()
res.get("key", {}).get("key")
AttributeError: 'NoneType' object has no attribute 'get'
Below are the ways I've tried to catch it, but didn't work:
if res is None or isinstance(res, type(None)) or len(res) == 0
The NoneType errors in question have len(req.text) = 16 ?
Vs +1k for the not NoneType errors.
Currently catching them this way:
if len(req.text) < 100: # Empty JSON Object
return None
But I am pretty sure this isn't the best practice.
Can someone help resolve this issue ?
UPDATE
print(type(res))
<class 'dict'>
print(res)
{'key': None}
SOLUTION
if res.get("key") is None:
return None
Should have inspected further.
MEA CULPA
I am realizing that the AttributeError was about the second .get("key") and not the former .get("key", {}) while I didn't include it (the 2nd get) in my original, unedited, post.
The type of res.get("key", {}) is None
Sorry & Thanks to all !
9 Replies 9
Can you explain how the middle options don't work? If res is None, I'd think either of the first two clauses of your or expression should catch it. If it's something other than None, I'd expect you to get a different exception. What is the contents of req.text when you say it's length 16?
Just if response is None:, or if response is not None: to ensure that is isn't None. You show something similar to that and say that it didn't work, but it will.
because it is possible that response is a list or number or even an string.
in that scenario is is not null but also you can't call that with a get. you can first check it is a json or not.
isinstance(res, dict)
Print out response before attempting to use it and see what it is. It likely has a different structure than what you expect.
Also, if you get an error, post the full error and not just a small fraction of it like AttributeError.
You might still be getting an AttributeError, but if you screen out the None values, it should say something other than 'NoneType' object has no attribute 'get'. What it does say should give you a hint at what the actual object is in that case. There must be two different failure modes, and you're only screening for one of them.