将Spotify API与Google Sheets对接:稳定获取数据的技术问询
用Spotify API对接Google Sheets获取稳定数据的步骤
1. 准备Spotify开发者凭证
- 登录Spotify开发者控制台,创建一个新应用
- 记录下应用的
Client ID和Client Secret - 在应用设置里添加重定向URI(比如
http://localhost:8080,仅用于初始化授权流程,后续脚本无需实际使用)
2. 实现访问令牌获取(Client Credentials Flow)
因为你要获取的是公开数据,用Client Credentials Flow足够,无需用户授权。在Google Apps Script里写一个获取token的函数:
function getSpotifyToken() { const clientId = "你的Client ID"; const clientSecret = "你的Client Secret"; const authString = Utilities.base64Encode(`${clientId}:${clientSecret}`); const options = { method: "post", headers: { "Authorization": `Basic ${authString}`, "Content-Type": "application/x-www-form-urlencoded" }, payload: "grant_type=client_credentials" }; const response = UrlFetchApp.fetch("https://accounts.spotify.com/api/token", options); const json = JSON.parse(response.getContentText()); return json.access_token; }
注意:token有效期为1小时,建议用缓存减少重复请求:
function getCachedSpotifyToken() { const cache = CacheService.getScriptCache(); let token = cache.get("spotify_token"); if (!token) { token = getSpotifyToken(); cache.put("spotify_token", token, 3500); // 缓存3500秒,比有效期短一点避免过期 } return token; }
3. 调用API获取目标数据
获取播放列表粉丝数
function getPlaylistFollowers(playlistId) { const token = getCachedSpotifyToken(); const url = `https://api.spotify.com/v1/playlists/${playlistId}`; const options = { headers: { "Authorization": `Bearer ${token}` } }; const response = UrlFetchApp.fetch(url, options); const json = JSON.parse(response.getContentText()); return json.followers.total; }
在Google Sheets单元格直接调用:=getPlaylistFollowers("播放列表ID")
获取艺人粉丝数
function getArtistFollowers(artistId) { const token = getCachedSpotifyToken(); const url = `https://api.spotify.com/v1/artists/${artistId}`; const options = { headers: { "Authorization": `Bearer ${token}` } }; const response = UrlFetchApp.fetch(url, options); const json = JSON.parse(response.getContentText()); return json.followers.total; }
单元格调用:=getArtistFollowers("艺人ID")
关于月听众数据
注意:Spotify公开Web API不提供艺人月听众数据,该数据仅对艺人本人通过Spotify for Artists开放。如果需要此数据,需艺人授权并使用Spotify for Artists专属API接口。
4. 优化与注意事项
- API配额:Spotify API有请求配额限制,避免短时间内发起大量请求
- 错误处理:建议在函数中添加try-catch块,处理token过期(401)、资源不存在(404)等异常
- 批量处理:若需批量获取多个播放列表/艺人数据,可编写批量处理函数,减少重复请求开销
内容的提问来源于stack exchange,提问作者devR
相关产品推荐
相关产品推荐

