R/search_artists.R

Defines functions search_artists

Documented in search_artists

#' @title Search artists based on given input
#' @description Connects with the Spotify API and returns output from the href <https://api.spotify.com/v1/search/>
#' @param artist_name Required. Get Spotify Catalog information about artists that match this input.
#' @param output Type of output to return from the request. Default: tidy.
#' @param limit Maximum number of results to return. Should be between 1 and 50. Default: 20.
#' @param offset The index of the first result to return. Default: 0.
#' @param token A valid access token from the Spotify Accounts service: see 
#' <https://developer.spotify.com/documentation/general/guides/authorization-guide/> for details. Default: my_token.
#' @return Default: returns a tidy dataframe with a selection of the response. Alternatively, when output is set to raw, it returns the raw output from the
#' request, or When output is set to id, it returns only the id.
#' @export
#' @importFrom httr add_headers
#' @importFrom httr content
#' @importFrom httr GET
#' @importFrom purrr map
#' @importFrom purrr map_chr
#' @importFrom purrr modify_depth
#' @importFrom magrittr %>%

search_artists <- function(artist_name, output = c("tidy", "raw", "id"), limit = 20, offset = 0, token = my_token){
  
  output <- match.arg(output)
  
  response = content(GET("https://api.spotify.com/v1/search/", query = list(q = artist_name, type = "artist", limit = limit, offset = offset), add_headers(Authorization = token)))
  items = response$artists$items
  
  tidy <- data.frame(
    artist = map_chr(items, "name"),
    artist_id = map_chr(items, "id"),
    followers = map(items, "followers") %>% map_chr("total"),
    popularity = map_chr(items, "popularity"),
    genres = map(items, "genres") %>% map_chr(paste, collapse = ", ")
  )
  
  id = tidy$artist_id
  
  out <-  switch(output,
                 tidy = tidy,
                 raw = response,
                 id = id)
  out
}

Try the spotidy package in your browser

Any scripts or data that you put into this service are public.

spotidy documentation built on March 16, 2021, 5:06 p.m.