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

PyScript如何向Spotify API传入授权令牌并获取内容?

在GitHub Pages上调用Spotify API的授权令牌问题

我在GitHub Pages静态服务器上搭建网站,尝试调用Spotify API获取最近播放的曲目,但在授权令牌传入环节遇到问题。

我尝试的代码

<py-script>
  from pyodide.http import pyfetch
  import json
  import asyncio
  import re
  
  response = await pyfetch(
    url="https://api.spotify.com/v1/me/player/currently-playing", 
    headers={'authorization': --insert auth token here--}, 
    method="GET"
  )
  cal= str('C')
  output = f'{await response.json()}'
  
  def jj(output):
    str1 = output.replace("\'", "\"")
    st= json.loads(str1)
    return st
  
  pyscript.write(jj(output))
</py-script>

遇到的错误信息

JsException(PythonError: Traceback (most recent call last):
  File "/lib/python3.10/asyncio/futures.py", line 201, in result
    raise self._exception
  File "/lib/python3.10/asyncio/tasks.py", line 232, in __step
    result = coro.send(None)
  File "/lib/python3.10/site-packages/_pyodide/_base.py", line 500, in eval_code_async
    await CodeRunner(
  File "/lib/python3.10/site-packages/_pyodide/_base.py", line 353, in run_async
    await coroutine
  File "", line 7, in 
  File "/lib/python3.10/site-packages/pyodide/http.py", line 139, in json
    self._raise_if_failed()
  File "/lib/python3.10/site-packages/pyodide/http.py", line 107, in _raise_if_failed
    raise OSError(
OSError: Request for https://api.spotify.com/v1/me/player/currently-playing failed with status 400: )

问题分析与解决建议

  1. 授权头格式错误
    Spotify API要求Authorization头必须是Bearer <你的令牌>格式,你当前的代码里只填了令牌,缺少Bearer 前缀。正确的headers写法应该是:
headers={'Authorization': 'Bearer 你的授权令牌内容'}
  1. 前端硬编码令牌的安全风险
    GitHub Pages是纯静态页面,直接把授权令牌写在前端代码里会导致令牌泄露,任何人都可以拿到你的令牌调用API操作你的Spotify账号。正确的做法是使用Spotify授权码流程(Authorization Code Flow),通过后端服务获取临时访问令牌,前端再调用后端接口间接获取数据;若没有后端资源,可考虑使用Implicit Grant Flow(仅适合非敏感操作)获取短期令牌。

  2. 代码冗余处理
    你把response.json()转成字符串再替换引号重新解析的操作完全没必要,await response.json()直接返回JSON对象,不需要额外处理。比如:

data = await response.json()
# 直接使用data即可,比如获取曲目名称:data['item']['name']
  1. 增加错误排查逻辑
    建议先检查响应状态码,并获取具体错误信息,方便定位问题:
if response.status != 200:
    error_msg = await response.text()
    print(f"请求失败:{response.status},详情:{error_msg}")
else:
    data = await response.json()
    # 处理数据

修正后的示例代码

<py-script>
  from pyodide.http import pyfetch
  import json

  async def get_current_playing():
    # 注意:这里的令牌应该通过合法授权流程获取,不要硬编码在前端!
    auth_token = "你的临时访问令牌"
    headers = {"Authorization": f"Bearer {auth_token}"}
    
    try:
      response = await pyfetch(
        url="https://api.spotify.com/v1/me/player/currently-playing",
        headers=headers,
        method="GET"
      )
      
      if response.status == 200:
        track_data = await response.json()
        track_name = track_data["item"]["name"]
        artist = track_data["item"]["artists"][0]["name"]
        pyscript.write("playing-status", f"当前播放:{track_name} - {artist}")
      elif response.status == 204:
        pyscript.write("playing-status", "当前没有播放任何曲目")
      else:
        error_details = await response.text()
        pyscript.write("playing-status", f"请求失败(状态码{response.status}):{error_details}")
    except Exception as e:
      pyscript.write("playing-status", f"出错:{str(e)}")

  await get_current_playing()
</py-script>

<div id="playing-status"></div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 01:55:35