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

使用Spotify API时持续出现401错误(No token provided)求助

解决Spotify API 401 "No token provided"错误

核心错误原因

你的代码里存在一个拼写错误:在searchArtist函数的请求头中,你把授权字段写成了Authorizations(多了一个s),而Spotify API要求的标准字段名是Authorization。这个错误导致服务端无法识别你传入的token,因此返回No token provided的401错误。

修正后的代码

修改searchArtist函数里的headers字段名即可:

import json
from requests import post, get
import base64

def get_token():
    auth_string = CLIENT_ID + ":" + CLIENT_SECRET
    auth_bytes = auth_string.encode("utf-8")
    auth_base64 = str(base64.b64encode(auth_bytes), "utf-8")

    url = "https://accounts.spotify.com/api/token"
    headers = {
        "Authorization" : "Basic " + auth_base64,
        "Content-Type" : "application/x-www-form-urlencoded"
    } 

    data = {"grant_type" : "client_credentials"}
    result = post(url, headers=headers, data=data)
    json_result = json.loads(result.content)
    token = json_result["access_token"]
    return token

def searchArtist(token, artist_name):
    url = "https://api.spotify.com/v1/search"
    headers = {
        # 修正字段名:移除多余的`s`
        "Authorization" : "Bearer " + token
    }
    query = f"?q={artist_name}&type=artist&limit=1"
    query_url = url + query
    result = get(query_url, headers=headers)
    data = result.json()
    print(data)

myToken = get_token()
searchArtist(myToken, "ACDC")

额外注意事项

你提到要提取用户热门曲目,但当前使用的client_credentials授权模式仅能访问Spotify公开数据(如艺术家、公开曲目信息),无法访问用户私有数据(包括个人热门曲目)。如果要获取用户热门曲目,需要使用Authorization Code Flow(或PKCE版本),引导用户授权你的应用访问其个人数据,获取带用户权限的token后,才能调用/v1/me/top/tracks这类私有接口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 10:12:15