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.0 (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(tidyverse)
library(knitr)

beatles %>% 
    count(key_mode, sort = TRUE) %>% 
    head(5) %>% 
    kable()
key_moden
D major24
G major21
A major13
F major12
C major11

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(track.name, artist.name, track.album.name, played_at) %>% 
    kable()
track.nameartist.nametrack.album.nameplayed_at
Hardened Chord - Regis RemixStaveAfter the Social2019-07-12 19:04:29
CellsBlenkShelter2019-07-12 18:57:59
Suspension Of Consciousness - Original mixFlaminiaTHEOTHERSIDE 012019-07-12 18:52:32
KeralaBonoboMigration2019-07-12 18:46:58
LinkedBonoboLinked2019-07-12 18:45:31

Find your all time favorite artists

get_my_top_artists_or_tracks(type = 'artists', time_range = 'long_term', limit = 5) %>% 
    select(name, genres) %>% 
    rowwise %>% 
    mutate(genres = paste(genres, collapse = ', ')) %>% 
    ungroup %>% 
    kable()
namegenres
Radioheadalternative rock, art rock, melancholia, modern rock, oxford indie, permanent wave, rock
Flying Lotusalternative hip hop, escape room, experimental hip hop, glitch, glitch hop, hip hop, indietronica, intelligent dance music, jazztronica, wonky
Onraalternative hip hop, chillhop, trip hop, wonky
Teebsabstract beats, bass music, chillwave, wonky
Pixiesalternative rock, boston rock, garage rock, indie rock, modern rock, new wave, noise pop, permanent wave, rock

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
Impossible KnotsThom YorkeANIMA
I Am a Very Rude PersonThom YorkeANIMA
TrafficThom YorkeANIMA
Not The NewsThom YorkeANIMA
RunwayawayThom YorkeANIMA

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(track_name, valence) %>% 
    head(5) %>% 
    kable()
track_namevalence
Passover - 2007 Remaster0.941
Colony - 2007 Remaster0.808
Atrocity Exhibition - 2007 Remaster0.787
A Means to an End - 2007 Remaster0.752
Interzone - 2007 Remaster0.746

Now if only there was some way to plot joy…

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

library(ggjoy)

ggplot(joy, aes(x = valence, y = album_name)) + 
    geom_joy() + 
    theme_joy() +
    ggtitle("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

Sentiment analysis of musical taste: a cross-European comparison, Paul Elvers

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

KendRick LamaR, David K. Laing

Vilken är Kents mest deprimerande låt? (What is Kent’s most depressing song?), Filip Wästberg

Чёрное зеркало Arcade Fire (Black Mirror Arcade Fire), TheSociety

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

Long Distance Calling: Data Science meets Post-Rock…, Sebastian Kuhn

Copy Link

Version

Install

install.packages('spotifyr')

Monthly Downloads

155

Version

2.1.1

License

MIT + file LICENSE

Issues

Pull Requests

Stars

Forks

Last Published

December 15th, 2022

Functions in spotifyr (2.1.1)

get_album_data

Retrieve artist discography with song lyrics and audio info
create_playlist

Create a playlist for a Spotify user. (The playlist will be empty until you add tracks.)
check_users_following

Check if Users Follow a Playlist
add_tracks_to_playlist

Add one or more tracks to a user<U+2019>s playlist.
change_playlist_details

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

Check if Current User Follows Artists or Users
get_album

Get Spotify catalog information for a single album.
dedupe_album_names

Remove duplicate album names
get_featured_playlists

Get a list of Spotify featured playlists (shown, for example, on a Spotify player<U+2019>s <U+2018>Browse<U+2019> tab).
get_artist_albums

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

Get a playlist owned by a Spotify user.
get_artist

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

Search for artists by genre
follow_artists_or_users

Add the current user as a follower of one or more artists or other Spotify users.
follow_playlist

Add the current user as a follower of a playlist.
get_artists

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

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

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

Get audio feature information for all or part of an artists' discography.
get_my_top_artists_or_tracks

Get the current user<U+2019>s top artists or tracks based on calculated affinity.
get_label_artists

Search for artists by label
get_new_releases

Get a list of new album releases featured in Spotify (shown, for example, on a Spotify player<U+2019>s <U+201C>Browse<U+201D> tab).
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_user_audio_features

Get audio feature information for a users' playlists
set_my_repeat_mode

Set the repeat mode for the user<U+2019>s playback. Options are repeat-track, repeat-context, and off.
get_user_playlists

Get a list of the playlists owned or followed by a Spotify user.
seek_to_position

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

Get audio feature information for a single track identified by its unique Spotify ID.
get_playlist_tracks

Get full details of the tracks of a playlist owned by a Spotify user.
get_playlist_cover_image

Get the current image associated with a specific playlist.
get_category_playlists

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

Retrieve artist discography with song lyrics and audio info
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.
get_albums

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

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

Set the volume for the user<U+2019>s current playback device.
get_my_currently_playing

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

Skips to next track in the user<U+2019>s queue.
transfer_my_playback

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

Get detailed profile information about the current user (including the current user<U+2019>s username).
get_recommendations

Create a playlist-style listening experience based on seed artists, tracks and genres.
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_my_recently_played

Get Current User's Recently Played Tracks
get_my_followed_artists

Get the current user<U+2019>s followed artists.
get_my_devices

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

Remove the current user as a follower of a playlist.
get_spotify_access_token

Get Spotify Access Token
pause_my_playback

Pause playback on the user<U+2019>s account.
get_my_playlists

Get a list of the playlists owned or followed by the current Spotify user.
get_playlist_audio_features

Get features and popularity for all of a given set of playlists on Spotify
scopes

Valid scopes
search_spotify

Search for an item
pitch_class_lookup

Pitch class notation lookup
get_user_profile

Get public profile information about a Spotify user.
get_spotify_authorization_code

Get Spotify authorization Code
get_track_audio_analysis

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

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

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

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

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

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

Verify API result
spotifyr

spotifyr package
get_my_saved_tracks

Get a User's Saved Tracks
print.playlist

Print method for playlist object
remove_tracks_from_playlist

Remove one or more tracks from a user<U+2019>s playlist.
get_my_saved_albums

Get Current User's Saved Albums
tidy

Tidy a playlist
get_recommendations_all

Get recommendations for a submitted vector of track IDs, with no limit on the number of seed tracks
get_categories

Get a list of Spotify categories