Last.fm API Intro and Tutorial

Author

Alex Grotjan

Assignment 6: Learning a New API

1) Explanation of the Service [Last.fm API]

The Last.fm API connects to the service Last.fm, which is a type of music tracking service. It can track your listening activity across multiple platforms such as Spotify, Apple Music, and more. It is not a streaming service, but a personalized tracker for your music taste. The Last.fm API allows you to interact with the Last.fm database to get information about certain tracks and artists. You can get data about a track’s most popular tags assigned by users like <dance> or <happy> as well. You could also see things like the play count of a track and the duration. The API can be used to see more in-depth information about an artist like their most popular songs as well.

This API is useful to run analysis on listener behavior, especially since Last.fm data takes into account streams and play counts from multiple platforms like Spotify and Apple Music. Data about the most popular tags for each track is especially useful because it records what users associate with certain songs. Overall, the Last.fm API gives you access to data that can be used to better understand the listeners who use Last.fm, and what their preferences and associations are when it comes to music.

2) Tutorial/Setup

  • Create a Last.fm account (note: make an alternate account if you already have one to avoid sharing your own personal listening history)

    • Go to https://www.last.fm/join

    • Fill in the required fields to make a new account (username, email, password)

    • Click the box to confirm you are not a robot (if needed)

    • Agree to terms and conditions and click Sign Up

    • Confirm your email by going to the email you set up your account with and then selecting the email from Last.fm. Click verify email and log in

    • Now you have a new account for Last.fm!

  • Get an API key

    • Fill out the form: (only the fields below are required)

      • Contact Email: Same as email for account

      • Application name: Give your project a name (anything works)

      • Application description: Describe the purpose of the project (ex. Use data to learn about music trends)

      • Application Homepage: It does not need to be a live website. Use -> http://localhost

      • Click the box to confirm you are not a robot (if needed)

      • Click Submit

      • Copy the API key given

  • Create your own R script (you can copy and paste any of the code blocks on this webpage for use)

  • Install required packages

    # Run the code below in the COMMAND LINE (copy and paste into command line)
    
    install.packages(c("httr", "jsonlite", "tidyverse", "readr"))
  • Load in required packages

    library(tidyverse) # All the tidy things
    library(jsonlite)  # Converting json data into data frames
    library(magrittr)  # Extracting items from list objects using piping grammar
    library(httr)      # Interacting with HTTP verbs
  • Paste your API key in the green text below and run the code to save your API key in the environment (Be careful with your API key. Do not post it anywhere public. Keep it in your own R script where it is not available for others to see. )

    your_api_key <- "YOUR_API_KEY_HERE"

3) Example API Call

You can make an API call to the track.getInfo endpoint to get data about a specific track. You will get information about the name of the song, the artist, the duration, and more! If you want more info about this endpoint for the API, visit this link: https://www.last.fm/api/show/track.getInfo

Below is an example API call that uses functions to easily create a URL for the GET request and then make the request to then turn the response into a data frame. For this API you can only call for one track at a time, so the response should be 1 row with several columns recording attributes (artist name, playcount, etc.).

##### function to create URL #####
lastfm_api_GET_url <- 
  function(api_key, artist, track) {
    
    lastfm_endpint <- "http://ws.audioscrobbler.com/2.0/?method=track.getInfo"
    
    api_key <- paste("&api_key=",api_key, sep = "")
    artist <- paste("&artist=", URLencode(artist), sep = "")
    track <- paste("&track=", URLencode(track), sep = "")
    format <- "&format=json"
    
    lastfm_url <-
      paste0(lastfm_endpint,api_key,artist,track,format)
    
    return(lastfm_url)
  }

# Test the function and copy and paste the url into a browser to see that
# json format information was output on the window with data about the track
lastfm_api_GET_url(api_key = your_api_key,
                   artist = "Coldplay",
                   track = "Yellow")





##### Function to make GET request and create a data frame #####
lastfm_api_GET_df <- 
  function(api_key, artist, track){
    
    # Saves the URL for the GET request as an object
    lastfm_api_url <- lastfm_api_GET_url(api_key = your_api_key,
                                         artist = artist,
                                         track = track)
    
    # Makes GET request and turns it into a nested list
    track_list <- 
      lastfm_api_url %>% 
      GET() %>% 
      content(as = "text",
              encoding = "UTF-8") %>% 
      fromJSON() %>% 
      use_series(track)

    # Makes a string with comma seperated tags for the song 
    tags_string <- paste(track_list$toptags$tag$name, collapse = ", ")
    
    # Makes the nested list into a tibble so you can view it as a tidy data frame
    lastfm_df <- tibble(
      name = track_list$name,
      duration = track_list$duration,
      listeners = track_list$listeners,
      playcount = track_list$playcount,
      artist_name = track_list$artist$name,
      album_title = track_list$album$title,
      top_tags = tags_string) %>% 
      relocate(artist_name,name)
    
    return(lastfm_df)
  }

# Test to make sure the GET df function works and it returns a 1 row data frame
lastfm_df_TEST <- 
  lastfm_api_GET_df(api_key = your_api_key,
                    artist = "Coldplay",
                    track = "Yellow")

If you wanted to get data for multiple tracks, you would need to loop through different tracks and artist names in order to add more data to the table. Below is an example of how you may loop through multiple songs to get a table with multiple songs and their attributes.

# Define the songs you want.
# MAKE SURE THE SONG NAMES AND ARTISTS NAMES MATCH:
# "Yellow" and "Coldplay" are both the 1st value in the lists, "Jaded" and 
# "Spiritbox" are both the 2nd values in their lists, etc. 
song_names <- c("Yellow", "Jaded", "Not Like Us","Emergence")
artist_names <- c("Coldplay", "Spiritbox", "Kendrick Lamar","Sleep Token")

# Create a blank tibble that we will add data to using the loop
multiple_songs_df <- tibble()


##### Looping function to gather data for multiple songs #####
for(i in seq_along(song_names)) {
  
  lastfm_temp_df <- 
    lastfm_api_GET_df(api_key = your_api_key,
                                artist = artist_names[i],
                                track = song_names[i])
  
  multiple_songs_df <- bind_rows(multiple_songs_df, lastfm_temp_df)
  
  # status message
  paste("Song",i,"of",length(song_names),"collected", sep = " ") %>% 
    print()
  
  # pause system so we have time between API calls
  if (i<length(song_names)) {
    Sys.sleep(3)
  }
}

One issue you may run into is not getting the most popular version of the track. That is just a feature of this API endpoint. You would need to interact with other endpoints such as artist.getTopTracks in order to always get the most popular version of the song every time.

Once you have looped through the different songs you will get a data frame that looks something like the output below

# A tibble: 4 × 7
  artist_name    name        duration listeners playcount album_title   top_tags
  <chr>          <chr>          <dbl>     <dbl>     <dbl> <chr>         <chr>   
1 Coldplay       Yellow        269000   3398067  36516388 Parachutes    rock, a…
2 Spiritbox      Jaded         262000    197614   2694300 The Fear of … metalco…
3 Kendrick Lamar Not Like Us   275000   1807085  27711438 Not Like Us   Hip-Hop…
4 Sleep Token    Emergence     386000    201938   4585537 Emergence     Progres…

Conclusion

I hope that this tutorial was helpful for understanding the Last.fm API. This API is very useful to see detailed information about different tracks, and the inclusion of top_tags data is very useful for analyzing what listeners associate with their songs. Here is the link to the Last.fm API one more time so that you can explore it yourself. https://www.last.fm/api ->The endpoints are listed on the left side of the webpage.