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

使用Python调用SupportPal API遇认证错误求助

解决SupportPal API Python认证失败问题

你通过curl可正常访问SupportPal API:

curl.exe -i -u 'APIKEY:x' -X GET https://support.url.org/api/user/user/3697

但Python复现时持续触发认证错误:

Failed to authenticate because of bad credentials or an invalid authorization header

你的Python代码如下:

import requests
import json

url = "https://support.url.org/api/user/user/3697"

headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer: {APIKEY:x}"
}

response = requests.request("GET", url, headers=headers)
print(response.Text)

问题原因

curl的-u参数使用的是Basic HTTP认证,但你在Python代码里错误采用了Bearer认证的格式,且格式本身也不符合规范(Bearer后应跟空格而非冒号),同时Basic认证需要对用户名:密码格式的字符串做Base64编码后再放入请求头。

正确实现方式

方式一:使用requests自带的auth参数(推荐)

requests库内置了Basic认证的处理逻辑,直接传入用户名和密码即可,无需手动构造请求头:

import requests

url = "https://support.url.org/api/user/user/3697"

# 传入APIKEY作为用户名,x作为密码
response = requests.get(url, auth=('APIKEY', 'x'))
print(response.text)

方式二:手动构造Basic认证请求头

如果需要手动构造Authorization头,需先对APIKEY:x进行Base64编码:

import requests
import base64

url = "https://support.url.org/api/user/user/3697"
auth_credentials = "APIKEY:x"
# 先转为字节流,再做Base64编码,最后转回字符串
encoded_auth = base64.b64encode(auth_credentials.encode()).decode()

headers = {
    "Content-Type": "application/json",
    "Authorization": f"Basic {encoded_auth}"
}

response = requests.get(url, headers=headers)
print(response.text)

内容的提问来源于stack exchange,提问作者Nathan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 12:05:16