You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用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路径下,直接从根节点取值必然失败。

解决方法

  1. 修正键名拼写,并按照响应的嵌套层级正确获取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}"})
  1. 可选容错优化:使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 06:31:14