是否可以将 curl/json 与 tcl 一起使用并检索 spotify API 数据?

Is it possible to use curl/json with tcl and retrieve spotify API data?

我正在尝试在 TCL 中制作一个简单的 proc,它从 SPOTIFY API 获取有关我当前正在播放的曲目的数据。

欢迎任何想法。 :D

格式: GET https://api.spotify.com/v1/me/player/currently-playing

我需要发送这个:

curl -X "GET" "https://api.spotify.com/v1/me/player/currently-playing?market=ES&additional_types=episode" -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer BQAai*****8n-5zXrLypj********hsgafd"

(身份验证屏蔽码)

参考:https://developer.spotify.com/documentation/web-api/reference/

作为第一次剪辑,这里有一个非常简单的包装器:

proc curl args {
    # The options skip showing stuff you don't want in scripted form
    # They also enable following redirects; you probably want to do that!
    exec curl -s -S -L {*}$args
}

# Usually easiest to keep this sort of thing separate
set spotifyToken "BQAai*****8n-5zXrLypj********hsgafd"

# -G to force the use of the GET verb
set json [curl -G "https://api.spotify.com/v1/me/player/currently-playing?market=ES&additional_types=episode" -H "Accept: application/json" -H "Content-Type: application/json" -H "Authorization: Bearer $spotifyToken"]

我们可以进一步包装:

package require http;  # Standard part of Tcl
package require json;  # Part of tcllib

proc spotifyGet {api args} {
    global spotifyToken; # Assume variable set as earlier
    set url https://api.spotify.com/v1/$api?[http::formatQuery {*}$args]
    set options {-H "Accept: application/json" -H "Content-Type: application/json"}
    lappend options -H "Authorization: Bearer $spotifyToken"
    return [json::json2dict [curl -G $url {*}$options]]
}

set data [spotifyGet me/player/currently-playing market ES additional_types episode]
puts [dict get $data item name]

如果您正在做更严肃的 JSON 工作,请考虑使用 rl_json 库。您需要探索返回的数据以了解它。 (我无法测试;我不使用 Spotify。)

这是使用 Tcl 内置 http 支持的 Donald 解决方案的变体:

package require http; 
package require json;

package require tls
::http::register https 443 ::tls::socket

set spotifyToken "BQAai*****8n-5zXrLypj********hsgafd"

proc spotifyGet {api args} {
  global spotifyToken;
  set url https://api.spotify.com/v1/$api?[http::formatQuery {*}$args]

  dict set hdrs Authorization [list Bearer $spotifyToken]
  dict set hdrs Accept "application/json"

  set token [http::geturl $url \
                 -type "application/json" \
                 -headers $hdrs]

  if {[http::status $token] eq "ok"} {
    set responseBody [http::data $token]
  } else {
    error "Spotify call failed: [http::error $token]"
  }

  http::cleanup $token
  return [json::json2dict $responseBody]
}

set data [spotifyGet me/player/currently-playing market ES additional_types episode]

毕竟没那么复杂,但需要额外的依赖:TclTLS.