Spotify

Author

Heather White

Introduction

The service I selected is Spotify because it is one that I personally use very often and I have Spotify Premium. Someone would want to use this data to learn about what people are listening to and when they are listening to it.

Walkthrough

You can get the API by going to Spotify’s Web API page: https://developer.spotify.com/documentation/web-api

You log into your Spotify account and then you create an app. For the URI use http://localhost:1410/. Adding a website isn’t necessary, but I used http://www.xavier.edu/ and you do need to give it a name of your choosing. Then you will have access to the app credentials. This is what will be required for API authorization to obtain an access token. Then use the access token in the API requests

Packages

library(spotifyr)
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.3     ✔ readr     2.1.4
✔ forcats   1.0.0     ✔ stringr   1.5.0
✔ ggplot2   3.4.3     ✔ tibble    3.2.1
✔ lubridate 1.9.2     ✔ tidyr     1.3.0
✔ purrr     1.0.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(httpuv)
library(knitr)
library(lubridate)
library(purrr)

Set Up Authorization and Authentication

# Sys.setenv(SPOTIFY_CLIENT_ID = 'XXXX')
# Sys.setenv(SPOTIFY_CLIENT_SECRET = 'XXXX')

Access Token and Scopes

access_token <- get_spotify_authorization_code(scope = scopes()[c(7,8,14,15)])

Authentication

auth <- get_spotify_authorization_code(  client_id = Sys.getenv("SPOTIFY_CLIENT_ID"),
                                 client_secret = Sys.getenv("SPOTIFY_CLIENT_SECRET"),
                               scope = scopes()[c(7,8,14,15)])

Add Access Token to Authentication

access_token <- auth

Example

This is a call to the API to receive a list of my top songs, artists, and albums long term. I used mutate to rename some of the columns to make reading and following the table easier. I used get_my_top_artists_or_tracks to get the tracks. I limited the list to 20 of my top songs over the last few years. I also had to ensure I authenticated usage with authorization.

artist_song <- get_my_top_artists_or_tracks(type = 'tracks', time_range = 'long_term', limit = 20, authorization = auth) %>% 
  mutate('artist name' = map_chr(artists, function(x) x$name[1])) %>% 
  mutate('album name' = album.name) %>% 
  mutate('song name' = name) %>% 
  select('song name', 'artist name', 'album name')