Spotify API player/currently-playing接口未返回当前播放歌曲数据求助
问题描述
尝试通过Spotify API获取设备上正在播放的歌曲数据,使用Django ViewSet拉取数据,但API返回用户信息而非预期的歌曲进度、标题、时长等数据。
相关代码
Django ViewSet 片段
class Song(viewsets.ModelViewSets): .... room_code = request.data['room_code'] room = Room.objects.filter(code=room_code)[0] host = room.host endpoint = 'player/currently-playing' response = execute_spotify_api_request(host, endpoint) item = response.get('item') duration = item.get('duration_ms') progress = response.get('progress_ms') album_cover = item.get('album').get('images')[0].get('url') return Response(response, status=status.HTTP_200_OK)
Spotify API 请求工具函数
def execute_spotify_api_request(session_id, endpoint, post_=False, put_=False): tokens = get_user_tokens(session_id) headers = {'Content-Type': 'application/json', 'Authorization': "Bearer " + tokens.access_token} if post_: post(BASE_URL + endpoint, headers=headers) if put_: post(BASE_URL + endpoint, headers=headers) response = get(BASE_URL, {}, headers=headers) try: return response.json() except: return {'error': 'Could not retrieve a response'}
非预期的API返回数据
{ "display_name": "Tanatswamanyakara", "external_urls": { "spotify": "https://open.spotify.com/user/dlnsysel6bndktbvduz6cl79w" }, "followers": { "href": null, "total": 0 }, "href": "https://api.spotify.com/v1/users/dlnsysel6bndktbvduz6cl79w", "id": "dlnsysel6bndktbvduz6cl79w", "images": [], "type": "user", "uri": "spotify:user:dlnsysel6bndktbvduz6cl79w" }
解决方案
问题核心在于工具函数的URL拼接错误和请求方法bug,具体修复如下:
修正请求URL拼接
当前代码中get(BASE_URL, {}, headers=headers)仅请求了BASE_URL(即https://api.spotify.com/v1/me/),这正是返回用户信息的原因。需要将传入的endpoint拼接到URL中:response = get(BASE_URL + endpoint, {}, headers=headers)修复PUT请求的方法错误
处理put_参数时错误调用了post方法,应改为put:if put_: put(BASE_URL + endpoint, headers=headers)优化POST/PUT请求的响应处理(可选)
若需要获取POST/PUT请求的返回结果,需接收并返回响应数据,避免无效调用:if post_: response = post(BASE_URL + endpoint, headers=headers) return response.json() if put_: response = put(BASE_URL + endpoint, headers=headers) return response.json()验证权限范围
确保Spotify应用已申请user-read-currently-playing权限,否则即使URL正确,token无权限也无法获取播放数据。
内容的提问来源于stack exchange,提问作者Tanatswa
相关产品推荐
相关产品推荐

