skip to Main Content

I’m working with an API that has different json responses depending on success/failure. They are not HTTP errors, but codes in the json body.

There are two possible error codes (400 and 404), and then you have your successful API response.

Three examples below including a successful API call:

j1 = {'status': '400','message': 'invalid'}
j2 = {'status': '404','message': 'wrong_info'}
j3 = {'info': 'your_info','other_info':'54321'}

Let’s just say I get a response, but I have no idea what it is. (Let’s make it a successful response below):

api_response = j3

{'info': 'your_info','other_info':'54321'}

Depending on what it is, I’ll be adding data to a dataframe, or doing nothing:


for row in df:

    # do API call and get api_response

    # if the api response has an error code (first digit== 4), just skip it
    if api_response['status'][:1]=='4':

        pass

    # if it has an 'info' key, do something
    elif api_response['facebook']:

        print('Found My Info')

Checking for status: 400 / 404 is causing an error. I thought the else would take care of this?

KeyError                                  Traceback (most recent call last)
<ipython-input-168-7a657630291c> in <module>
----> 1 if api_response['status'][:1]=='4':
      2     pass
      3 else:
      4     if api_response['info']:
      5         print('Found My Info')

KeyError: 'status'

What I’ve tried

I’ve added a try except, but it feels like I’m just throwing things together and ignoring the problem. Is this an acceptable or ‘pythonic’ way of handling different responses like this? Also, am I using pass properly to skip the row if there’s a 400/404 status?

try:
    if api_response['status'][:1]=='4':
        pass
except:
    if api_response['info']:
        print('Found My Info')
Found My Info

2

Answers


  1. Checking for status: 400 / 404 is causing an error. I thought the else would take care of this?

    No, because you’re trying to access a key that doesn’t exist, so first you need to test whether it exists!

    if 'status' in api_response and api_response['status'] in ('400', '404'):
        print('bad request')
    elif 'info' in api_response:
        print('Found My Info', api_response['info'])
    
    Login or Signup to reply.
  2. you can use dict.get to return a default value if the key doesn’t exist.

    You can specify your own default value, otherwise it is None

    try:

    if api_response.get('status','')[:1]=='4':
    

    and:

    if api_response.get('info'):
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search