使用命令行连接到 Spotify API

nac*_*ter 1 curl spotify access-token

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

curl "https://api.spotify.com/v1/search?type=artist&q=<someartist>"
Run Code Online (Sandbox Code Playgroud)

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

{
  "error": {
    "status": 401,
    "message": "No token provided"
  }
}
Run Code Online (Sandbox Code Playgroud)

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

希望有人可以帮忙!

nac*_*ter 8

因此,我花了更多时间破译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
    
    Run Code Online (Sandbox Code Playgroud)
  3. 使用编码凭据请求授权,这为我提供了访问令牌:

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

     curl -H "Authorization: Bearer <my_access_token>" "https://api.spotify.com/v1/search?q=<some_artist>&type=artist"
    
    Run Code Online (Sandbox Code Playgroud)

所有可用端点都可以在这里找到: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 }')
Run Code Online (Sandbox Code Playgroud)

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

myscript.sh some_artist some_album
Run Code Online (Sandbox Code Playgroud)

它会输出专辑 URI。