调用API获取token后设置请求头触发KeyError问题求助
KeyError: 'acces_token' 问题排查与解决
操作背景
调用API获取Token的代码:
res = s.post('https://api-gw.interneturok.ru/api/v2/psp/tokens', json=payload)
API返回的核心数据结构:
{ "status": "200_OK", "data": { "psp": { "response": { "data": { "access_token": "...", "access_type": "Bearer", "expires_in": 3600 } } } } }
尝试设置请求头时执行的代码:
s.headers.update({'authorization': json.loads(res.content)['acces_token']})
触发错误:
KeyError: 'acces_token'
问题原因
- 键名拼写错误:代码中使用的
acces_token少写了一个s,API返回的正确键名是access_token。 - 层级访问错误:即便拼写正确,
access_token也不在响应的根层级,而是嵌套在data -> psp -> response -> data路径下,直接从根节点取值必然失败。
解决方法
- 修正键名拼写,并按照响应的嵌套层级正确获取Token,同时注意Authorization头需要带上认证类型前缀:
import json # 解析响应内容 response_json = json.loads(res.content) # 逐层获取Token和认证类型 token_data = response_json['data']['psp']['response']['data'] access_token = token_data['access_token'] auth_type = token_data['access_type'] # 设置请求头 s.headers.update({'authorization': f"{auth_type} {access_token}"})
- 可选容错优化:使用
dict.get()方法避免层级缺失时直接报错:
access_token = response_json.get('data', {}).get('psp', {}).get('response', {}).get('data', {}).get('access_token') if access_token: auth_type = response_json.get('data', {}).get('psp', {}).get('response', {}).get('data', {}).get('access_type', 'Bearer') s.headers.update({'authorization': f"{auth_type} {access_token}"}) else: print("Failed to retrieve access token")
内容的提问来源于stack exchange,提问作者Mercury
相关产品推荐
相关产品推荐

