curl - 使用命令行连接到 Spotify API
问题描述
我想使用命令行从 Spotify API 中检索信息,例如:
curl "https://api.spotify.com/v1/search?type=artist&q=<someartist>"
但是当我这样做时,我得到:
{
"error": {
"status": 401,
"message": "No token provided"
}
}
我已经在我的 Spotify 开发者帐户中创建了一个应用程序。有人可以指导我完成如何将我的凭据与我的搜索请求一起传递的过程吗?我不想编写应用程序或任何东西。我只想从命令行检索信息。
希望有人能帮忙!
解决方案
因此,我花了更多时间来解读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)。这是我所做的:
在https://developer.spotify.com/dashboard/applications的仪表板上创建应用程序并复制客户端 ID 和客户端密码
使用 base64 编码客户端 ID 和客户端密码:
echo -n <client_id:client_secret> | openssl base64
使用编码凭据请求授权,这为我提供了访问令牌:
curl -X "POST" -H "Authorization: Basic <my_encoded_credentials>" -d grant_type=client_credentials https://accounts.spotify.com/api/token
使用该访问令牌,可以向 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。
推荐阅读
- elasticsearch - Spring Data Elasticsearch with RestHighLevelClient for ES 6.0.1
- r - 如果数据框中缺少列,则添加列的整洁方法
- django - Django如何在查询集中标记用户特定的对象以发送到模板?
- php - PHP 在使用 POST 方法时没有更新我的数据
- amazon-web-services - AWS Lambda 函数无法访问 RedShift
- swift - 基于类型别名的 Swift 初始化结构
- python - (discord.py) 齿轮中的函数
- python - 两个巨大的密集矩阵的乘法 Hadamard-乘以一个稀疏矩阵
- javascript - 可选链接在 v-if Vue 2 中不起作用
- ubuntu - make: *** [ffbuild/common.mak:67: libavfilter/vf_nnedi.o] 错误 1