首页 > 解决方案 > 使用命令行连接到 Spotify API

问题描述

我想使用命令行从 Spotify API 中检索信息,例如:

curl "https://api.spotify.com/v1/search?type=artist&q=<someartist>"

但是当我这样做时,我得到:

{
  "error": {
    "status": 401,
    "message": "No token provided"
  }
}

我已经在我的 Spotify 开发者帐户中创建了一个应用程序。有人可以指导我完成如何将我的凭据与我的搜索请求一起传递的过程吗?我不想编写应用程序或任何东西。我只想从命令行检索信息。

希望有人能帮忙!

标签: curlspotifyaccess-token

解决方案


因此,我花了更多时间来解读https://developer.spotify.com/documentation/general/guides/authorization-guide/上的说明,实际上我找到了一个相当简单的解决方案。

我想要做的是通过搜索特定专辑从 Spotify Web API 检索 Spotify 专辑 URI。因为我不需要可刷新的访问令牌,也不需要访问用户数据,所以我决定使用客户端凭据授权流程(https://developer.spotify.com/documentation/general/guides/authorization -guide/#client-credentials-flow)。这是我所做的:

  1. 在https://developer.spotify.com/dashboard/applications的仪表板上创建应用程序并复制客户端 ID 和客户端密码

  2. 使用 base64 编码客户端 ID 和客户端密码:

    echo -n <client_id:client_secret> | openssl base64
    
  3. 使用编码凭据请求授权,这为我提供了访问令牌:

    curl -X "POST" -H "Authorization: Basic <my_encoded_credentials>" -d grant_type=client_credentials https://accounts.spotify.com/api/token
    
  4. 使用该访问令牌,可以向 API 端点发出不需要用户授权的请求,例如:

     curl -H "Authorization: Bearer <my_access_token>" "https://api.spotify.com/v1/search?q=<some_artist>&type=artist"
    

所有可用的端点都可以在这里找到:https ://developer.spotify.com/documentation/web-api/reference/

在我的情况下,我想以“艺术家专辑”格式读取终端中的输入并输出相应的 spotify URI,这正是以下 shell 脚本所做的:

#!/bin/bash
artist=$1
album=$2
creds="<my_encoded_credentials>"
access_token=$(curl -s -X "POST" -H "Authorization: Basic $creds" -d grant_type=client_credentials https://accounts.spotify.com/api/token | awk -F"\"" '{print $4}')
result=$(curl -s -H "Authorization: Bearer $access_token" "https://api.spotify.com/v1/search?q=artist:$artist+album:$album&type=album&limit=1" | grep "spotify:album" | awk -F"\"" '{print $4 }')

然后我可以像这样运行脚本:

myscript.sh some_artist some_album

它将输出专辑 URI。


推荐阅读