状态 401 消息 Spotify 的 API

问题描述 投票:0回答:1

我正在使用 Spotify 的 API 做一个项目,在观看并遵循一些示例后,我收到一条消息:

状态 401 消息未经授权。

这是当我尝试使用文档中的任何函数时,我已经阅读了有关令牌的信息并看到了一些解决方案,但大多数都是 JSON 格式的,而且我不知道 JSON,我仍在学习。

# Function to get the token
def token():
    """ 
    Function to get the token for the Spotify API, without this the API won't work.
    You don't have to change anything in this function.
    """
    auth_string = f"{SPOTIPY_CLIENT_ID}:{SPOTIPY_CLIENT_SECRET}"
    auth_bytes = auth_string.encode("utf-8")
    auth_encoded = base64.b64encode(auth_bytes)

    url = "https://accounts.spotify.com/api/token"
    headers = {
        "Authorization": f"Basic {auth_encoded.decode('utf-8')}",
        "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

# Function to get the authorization header
def get_auth_header(token):
    """
    Function to get the authorization header for the Spotify API.
    You don't have to change anything in this function.
    """
    return {"Authorization": f"Bearer {token}"}

def my_profile():
    """
    Function to get the profile of the user.
    """
    token_ = token()
    headers = get_auth_header(token_)
    url = "https://api.spotify.com/v1/me"
    result = get(url, headers=headers)
    return json.loads(result.content)


me = my_profile()
print(me)
python token spotify http-status-code-401
1个回答
0
投票

演出有点晚了。但我想我无论如何都会回答,因为问题尚未标记为已解决。

您正在尝试使用错误的令牌访问用户信息。您使用的令牌(client-credentials)用于获取非特定于用户的信息。如果您想访问用户信息,则必须使用授权令牌。获得授权令牌相当困难,因此您可能需要阅读 Spotify 开发者网站上的 authorizationauthorization token 页面。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.