如何在一个API请求中处理不同的响应代码?

2024-09-25 02:40:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用一个API,它根据成功/失败有不同的json响应。它们不是HTTP错误,而是json主体中的代码。你知道吗

有两个可能的错误代码(400和404),然后您就有了成功的API响应。你知道吗

以下三个示例包括一个成功的API调用:

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

假设我得到了回应,但我不知道是什么。(下面是一个成功的回答):

api_response = j3

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

根据它是什么,我将向数据帧添加数据,或者什么都不做:


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')

检查status: 400 / 404会导致错误。我以为else会处理这个?你知道吗

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'

我试过的

我添加了一个try except,但感觉就像是把东西放在一起,忽略了问题。这是一个可以接受的或'Python'的方式来处理不同的反应像这样?另外,如果有400/404状态,我是否正确地使用pass跳过该行?你知道吗

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

Tags: infoapijsonmessageifresponsemystatus
2条回答

如果键不存在,可以使用^{}返回默认值。你知道吗

您可以指定自己的默认值,否则为None

尝试:

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

以及:

if api_response.get('info'):

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

不,因为您试图访问一个不存在的密钥,所以首先需要测试它是否存在!你知道吗

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'])

相关问题 更多 >