【问题标题】:GET API call for multiple URLSGET API 调用多个 URL
【发布时间】:2017-05-26 11:49:07
【问题描述】:

我在 R 方面有大约一年的经验,但我真的很难把我的脑袋绕在循环上,我真的很感谢你们的任何解释以及答案!

我正在尝试使用 Spotify API 循环播放音乐类别列表(这是 API 术语,它们在 Spotify 应用中被称为流派/情绪)并检索播放列表列表。要检索一个类别的播放列表,我可以使用以下内容:

我想这是一个相当简单的问题,不需要测试和获取密钥。 如果需要,可以使用 Spotify 文档(链接如下)轻松获取密钥,如果需要,我可以帮助设置(对于这个或任何其他 Spotify 项目)。

#Setup up; Store keys and authenticate 
ClientID <- "************"
ClientSecret <- "***********"

#OAuth 
spotifyEndpoint <- oauth_endpoint(NULL, 
                                  "https://accounts.spotify.com/authorize", 
                                  "https://accounts.spotify.com/api/token")
spotifyApp <- oauth_app("spotify", ClientID, ClientSecret)
spotifyToken <- oauth2.0_token(spotifyEndpoint, spotifyApp)


#Create URL to call
CatPlaylist <- paste("https://api.spotify.com/v1/browse/categories/","funk","/playlists",sep="")

#Call api using GET
CatPlaylist <- httr::GET(CatPlaylist, spotifyToken)

#Transform results form JSON
CatPlaylist <- jsonlite::fromJSON(toJSON(content(CatPlaylist)))

#Transform into df
CatPlaylist <- t(data.frame(CatPlaylist$playlists$items$name))

我将如何循环以收集其他类别,有效地将“funk”替换为“party”或“chill”之类的东西。

编辑:下面添加的尝试 我尝试了以下方法,其中

Cats

保存每次调用的完整 URL。

final = NULL

for(i in 1:length(Cats)){
CatPlaylist <- paste("https://api.spotify.com/v1/browse/categories/",i,"/playlists",sep="")
CatPlaylist <- GET(CatPlaylist, spotifyToken)
CatPlaylist <- jsonlite::fromJSON(toJSON(content(CatPlaylist)))
  CatPlaylist <- t(data.frame(CatPlaylist$playlists$items$name))
final <- rbind(CatPlaylist,final)}

API 文档 https://developer.spotify.com/web-api/get-categorys-playlists/

系统信息:R 3.3.2 R Studio 版本 1.0.143 OS Sierra 10_12_3

提前致谢:)

【问题讨论】:

    标签: api loops spotify httr


    【解决方案1】:

    找到了解决方案。这种与循环的斗争,因此欢迎提出任何建议,但与此同时,解决方案如下,以防其他人需要答案!

    #Get category playlist -  this works and returns a DF with rownames as categories. If country is not specified the API will return results which apply to all countries.
    my.list <-list()
    my.listOwner <-list()
    
    for(i in 1:length(Categories$id)){
      CatPlaylist <- paste0("https://api.spotify.com/v1/browse/categories/",Categories$id[i],"/playlists?limit=50&country=GB",sep="")
      miss.id <- Categories$id[i]
      list.name<- as.character(miss.id)
      a <- GET(CatPlaylist, spotifyToken)
      b <- jsonlite::fromJSON(toJSON(content(a)))
      my.list[[list.name]] <-data.frame(unlist(b$playlists$items$name))
      my.listOwner[[list.name]] <-data.frame(unlist(b$playlists$items$owner$id))
    }
    
    final <-do.call(rbind,my.list)
    finalOwner <- do.call(rbind,my.listOwner)
    

    【讨论】:

      猜你喜欢
      • 2018-03-23
      • 2018-04-12
      • 2020-05-14
      • 1970-01-01
      • 2013-04-22
      • 2013-11-26
      • 2014-10-14
      • 1970-01-01
      • 2019-03-21
      相关资源
      最近更新 更多