Skip to main content
 首页 » 编程设计

python之如何处理 API 请求中的不同响应码

2025年05月04日19duanxz

我正在使用一个 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,但感觉就像我只是把事情放在一起而忽略了这个问题。这是处理像这样的不同响应的可接受或“pythonic”方式吗?此外,如果存在 400/404 状态,我是否正确使用 pass 来跳过该行?

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

请您参考如下方法:

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

不,因为你试图访问一个不存在的 key ,所以首先你需要测试它是否存在!

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