j doe j doe - 6 months ago 27
Python Question

API error handling

So, I am using API calls to get some json data, and I am using a for loop to execute the call using multiple ids which will return different data based on the user's id. So basically we need to update the permissions for some of our users so the json data looks somewhat like this for the users without permissions:

{"meta":{"httpStatus":"401 - Unauthorized","error":{"errorMessage":"Insufficient

and this for users with the permissions:

{"id":"dsafsad","name":"Test","ownerId":"sdfasdfa","lastModified":"2016","isActive":true}],"nextPage":null},"meta":{"httpStatus":"200 - OK","requestId":"3242343"}}

so my question is if I have a big response with many results both with and without permissions how could I only pull the ids from the users with permissions, and exclude the ones without the permissions.

Say the response is stored in the variable "data" and the ids that I am looking for will be stored in "requestId" this is the code I tried:

requestId = request_id = [element['requestId'] for element in data['result']['elements']]

from this code I receive the a TypeError, and it doesn't recognize 'result' because the first response is a user without the correct permissions.


If you have control over your JSON:

One potential solution would be to consturct your json such that there's a parent node which describes the permissions of the returned result. For example:

{"permissions": false,
    {"meta":{"httpStatus":"401 - Unauthorized","error": 
    {"errorMessage":"Insufficient permissions.","errorCode":"ARH_8.5"},


{"permissions": true, 
ttpStatus":"200 - OK","requestId":"3242343"}}}

With this setup, just read the first value, and then structure your json-parsing code accordingly.

If your don't have control over the JSON:

In this case, you have to figure out which request you're receiving before you can really process it. One way to do this would be to read the names of the top keys.

In the case of the correct response, you could do something like this:

parsed_json = json.loads(json_string)
# The key "result" is only in the sucess response, not in the error response
if "result" in parsed_json: 
  # Success
  # Error