Learn R Programming

⚠️There's a newer version (2.2.4) of this package.Take me there.

spotifyr

Overview

spotifyr is an R wrapper for pulling track audio features and other information from Spotify’s Web API in bulk. By automatically batching API requests, it allows you to enter an artist’s name and retrieve their entire discography in seconds, along with Spotify’s audio features and track/album popularity metrics. You can also pull song and playlist information for a given Spotify User (including yourself!).

Installation

CRAN version 2.1.1 (recommended)

install.packages('spotifyr')

Development version

devtools::install_github('charlie86/spotifyr')

Authentication

First, set up a Dev account with Spotify to access their Web API here. This will give you your Client ID and Client Secret. Once you have those, you can pull your access token into R with get_spotify_access_token().

The easiest way to authenticate is to set your credentials to the System Environment variables SPOTIFY_CLIENT_ID and SPOTIFY_CLIENT_SECRET. The default arguments to get_spotify_access_token() (and all other functions in this package) will refer to those. Alternatively, you can set them manually and make sure to explicitly refer to your access token in each subsequent function call.

Sys.setenv(SPOTIFY_CLIENT_ID = 'xxxxxxxxxxxxxxxxxxxxx')
Sys.setenv(SPOTIFY_CLIENT_SECRET = 'xxxxxxxxxxxxxxxxxxxxx')

access_token <- get_spotify_access_token()

Authorization Code Flow

For certain functions and applications, you’ll need to log in as a Spotify user. To do this, your Spotify Developer application needs to have a callback url. You can set this to whatever you want that will work with your application, but a good default option is http://localhost:1410/ (see image below). For more information on authorization, visit the offical Spotify Developer Guide.

Usage

What Was the Beatles’ Favorite Key?

library(spotifyr)
beatles <- get_artist_audio_features('the beatles')
library(dplyr)
library(purrr)
library(knitr)

beatles %>% 
    count(key_mode, sort = TRUE) %>% 
    head(5) %>% 
    kable()
key_moden
C major104
D major98
G major82
A major76
E major62

Get your most recently played tracks

library(lubridate)

get_my_recently_played(limit = 5) %>% 
    mutate(
        artist.name = map_chr(track.artists, function(x) x$name[1]),
        played_at = as_datetime(played_at)
        ) %>% 
    select(
      all_of(c("track.name", "artist.name", "track.album.name", "played_at"))
      ) %>% 
    kable()
track.nameartist.nametrack.album.nameplayed_at
A Case of YouTristenA Case of You2021-06-14 09:54:44
Paper CupReal EstatePaper Cup2021-06-10 20:20:11
Wrong with YouTristenWrong with You2021-06-10 20:17:24
Animal - EditLUMPAnimal2021-06-10 20:13:21
Streets Of Your TownDOPE LEMONStreets Of Your Town2021-06-10 18:23:00

Find Your All Time Favorite Artists

get_my_top_artists_or_tracks(type = 'artists', 
                             time_range = 'long_term', 
                             limit = 5) %>% 
    select(.data$name, .data$genres) %>% 
    rowwise %>% 
    mutate(genres = paste(.data$genres, collapse = ', ')) %>% 
    ungroup %>% 
    kable()
namegenres
Japanese Breakfastart pop, bubblegrunge, eugene indie, indie pop, indie rock, philly indie
Haley Bonarmelancholia, stomp and holler
Balthazarbelgian indie, belgian rock, dutch indie, dutch rock, ghent indie
Buildings Breedingindie fuzzpop
Angus & Julia Stoneaustralian indie folk, indie folk, stomp and holler

Find your favorite tracks at the moment

get_my_top_artists_or_tracks(type = 'tracks', 
                             time_range = 'short_term', 
                             limit = 5) %>% 
    mutate(
        artist.name = map_chr(artists, function(x) x$name[1])
        ) %>% 
    select(name, artist.name, album.name) %>% 
    kable()
nameartist.namealbum.name
Hot & HeavyLucy DacusHot & Heavy
Sea UrchinMystic BravesSea Urchin
HumanFreedom FryHuman
Hot MotionTemplesHot Motion
Animal - EditLUMPAnimal

What’s the most joyful Joy Division song?

My favorite audio feature has to be “valence,” a measure of musical positivity.

joy <- get_artist_audio_features('joy division')
joy %>% 
    arrange(-valence) %>% 
    select(.data$track_name, .data$valence) %>% 
    head(5) %>% 
    kable()
track_namevalence
Passover - 2020 Digital Master0.946
Passover - 2007 Remaster0.941
Colony - 2020 Digital Master0.829
Colony - 2007 Remaster0.808
Atrocity Exhibition - 2020 Digital Master0.790

Now if only there was some way to plot joy…

Joyplot of the emotional rollercoasters that are Joy Division’s albums

library(ggplot2)
library(ggridges)

ggplot(
    joy, 
    aes(x = valence, y = album_name)
    ) + 
geom_density_ridges() + 
theme_ridges() +
labs(title = "Joyplot of Joy Division's joy distributions", 
     subtitle = "Based on valence pulled from Spotify's Web API with spotifyr")

Sentify: A Shiny app

This app, powered by spotifyr, allows you to visualize the energy and valence (musical positivity) of all of Spotify’s artists and playlists.

Dope Stuff Other People Have Done with spotifyr

The coolest thing about making this package has definitely been seeing all the awesome stuff other people have done with it. Here are a few examples:

Exploring the Spotify API with R: A tutorial for beginners, by a beginner, Mia Smith

Blue Christmas: A data-driven search for the most depressing Christmas song, Caitlin Hudon

Sente-se triste quando ouve “Amar pelos dois”? Não é o único (Do you feel sad when you hear “Love for both?” You’re not alone), Rui Barros, Rádio Renascença

Using Data to Find the Angriest Death Grips Song, Evan Oppenheimer

Hierarchical clustering of David Bowie records, Alyssa Goldberg

tayloR, Simran Vatsa

Code of Conduct

Please note that the spotifyr project is released with a Contributor Code of Conduct. By contributing to this project, you agree to abide by its terms.

Copy Link

Version

Install

install.packages('spotifyr')

Monthly Downloads

1,503

Version

2.2.1

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Maintainer

Daniel Antal

Last Published

June 17th, 2021

Functions in spotifyr (2.2.1)

get_artist_audio_features

Get Audio Features For Artists' Discography
check_me_following

Check Me Following
get_artist_albums

Get Spotify catalog information for multiple artists identified by their Spotify IDs.
follow_playlist

Add Current User to Followers of Playlist.
follow_artists_or_users

Add Current User as Follower Artists or Other Users
get_featured_playlists

Get List of Spotify Featured Playlists
get_my_recently_played

Get Current User's Recently Played Tracks
get_artists

Get Spotify catalog information for multiple artists identified by their Spotify IDs.
get_my_profile

Get User Profile Information
get_artist_top_tracks

Get Spotify catalog information about an artist<U+2019>s top tracks by country.
get_category_playlists

Get a list of Spotify playlists tagged with a particular category.
add_tracks_to_playlist

Add Tracks to User<U+2019>s Playlist
get_categories

Get a list of Spotify categories
change_playlist_details

Change a playlist<U+2019>s name and public/private state. (The user must, of course, own the playlist.)
get_category

Get a single category used to tag items in Spotify (on, for example, the Spotify player<U+2019>s <U+201C>Browse<U+201D> tab).
get_my_currently_playing

Get the object currently being played on the user<U+2019>s Spotify account.
get_my_devices

Get information about a user<U+2019>s available devices.
get_related_artists

Get Spotify catalog information about artists similar to a given artist. Similarity is based on analysis of the Spotify community<U+2019>s listening history.
get_recommendations

Create a playlist-style listening experience based on seed artists, tracks and genres.
get_recommendations_all

Get Recommendations for Unlimited Vector of Track IDs
get_label_artists

Search for artists by label
get_my_followed_artists

Get My Followed Artists
get_my_current_playback

Get information about the user<U+2019>s current playback state, including track, track progress, and active device.
get_my_saved_albums

Get Current User's Saved Albums
get_discography

Retrieve Artist Discography with Song Lyrics and Audio Info
get_my_playlists

Get List of My Playlists
pause_my_playback

Pause Playback
get_playlist_cover_image

Get Image Associated with Playlist
get_spotify_authorization_code

Get Spotify Authorization Code
get_playlist_tracks

Get Details of User Playlist Tracks.
get_track

Get Spotify catalog information for a single track identified by its unique Spotify ID.
skip_my_playback_previous

Skips to previous track in the user<U+2019>s queue.
get_my_saved_tracks

Get User's Saved Tracks
get_user_playlists

Get List of User Playlists
get_playlist

Get User Playlist
get_track_audio_analysis

Get a detailed audio analysis for a single track identified by its unique Spotify ID.
scopes

Valid Authorization Scopes
get_track_audio_features

Get audio features of tracks
get_genre_artists

Search for Artists by Genre
search_spotify

Search for an Item
start_my_playback

Skips to previous track in the user<U+2019>s queue.
unfollow_playlist

Remove Current User from Followers of Playlist.
is_uri

Check if a string matches the pattern of a Spotify URI
get_spotify_access_token

Get Spotify Access Token
get_tracks

Get Spotify catalog information for a single track identified by its unique Spotify ID.
print.playlist

Print method for playlist object
get_user_audio_features

Get User Playlist Audio Features
get_playlist_audio_features

Get Features and Popularity of Playlists on Spotify
spotifyr

spotifyr package
get_user_profile

Get User Public Profile Information
tidy

Tidy a Playlist
get_artist

Get Spotify catalog information for a single artist identified by their unique Spotify ID.
check_users_following

Check if Users Follow a Playlist
get_albums

Get Spotify catalog information for multiple albums identified by their Spotify IDs.
verify_result

Verify API Result
set_my_repeat_mode

Set User Playback Mode
seek_to_position

Seeks to the given position in the user<U+2019>s currently playing track.
transfer_my_playback

Transfer playback to a new device and determine if it should start playing.
toggle_my_shuffle

Toggle shuffle on or off for user<U+2019>s playback.
pitch_class_lookup

Pitch class notation lookup
get_new_releases

Get New Releases
get_my_top_artists_or_tracks

Get User<U+2019>s Top Artists or Tracks
%>%

Pipe operator
remove_tracks_from_playlist

Remove Tracks from User<U+2019>s Playlist
set_my_volume

Set User Device Volume
skip_my_playback

Skips to Next Track
create_playlist

Create Playlist for User
get_album_tracks

Get Spotify catalog information about an album<U+2019>s tracks. Optional parameters can be used to limit the number of tracks returned.
dedupe_album_names

Remove duplicate album names
get_album

Get Spotify catalog information for a single album.
validate_parameters

Asssertion for Correct API Requests.
validate_type_artist_or_user

Validate type paramter for 'artists' or 'user'.
validate_limit

Validate limit paramater
validate_country

Validate country parameter
validate_include_meta_info

Validate include_meta_info parameter
validate_type_artists_or_tracks

Validate type paramter for 'artists' or 'tracks'
validate_locale

Validate locale parameter
validate_volume_percent

Validate volume percent parameter
validate_position_ms

validate position_ms parameter
validate_state

validate state paramater
validate_time_range

validate time_range parameter
validate_market

Validate market parameter
validate_offset

Validate offset parameter