Archiving Spotify playlists

Music Non-Stop

Article from Issue 167/2014

For a monthly fee, the Spotify streaming service beams music onto your desktop or phone. To intensify the groove, Perlmeister Mike Schilli archived his Spotify playlists for eternity using an OAuth-protected web API.

The media beat is leaving legacy data carriers behind – and increasingly heading online. Faster even than newspapers are being replaced by e-papers, CDs are losing their original significance, with more and more consumers streaming music and movies.

At the same time, a change in licensing is on the horizon: A Blu-ray disk that you purchase and just view once often turns out to be a dust-catcher after a single evening's viewing pleasure; it just occupies valuable living space on specially designed shelves expensively acquired for nothing but this purpose. Three moves later, the owner is likely to sell the rarely touched box at the local flea market. So, why would you actually want to own copies of music and film products?

Marketers in a State of Shock

The established music marketers slept right through the trend. These "gramophone companies" would prefer to uphold their 100-year-old business model, and some artists are complaining, too  [1]  – whatever, I have my sights firmly set on the future already. Third-party providers, such as the video streamer Netflix in the United States, Canada, and the UK (and soon also in other European countries [2]) or music-only services like Pandora, Rhapsody, or Spotify [3] are making quite a good living out of online rental.

With these services, the customer does not acquire any digital content as a one-off purchase but pays a monthly subscription fee. In return, the provider undertakes to serve the customers via the Internet from a repertoire of millions of songs or movies. They either run on your PC; on small boxes like the Roku, Apple TV, Chromecast, or Amazon Fire; on your TV set; or directly on your Smartphone.

Some music rental providers offer a free radio program, in which the customer approximately defines the style but does not directly select any tracks. At times, annoying commercials interrupt your musical enjoyment. However, commercial versions offer a free choice of tracks from a more or less impressive catalogue, depending on the provider.

Subscribers can put together playlists (Figures  1 and  2) so their favorites reach the digital stage faster. The system is extremely convenient  – as long as you remain a paying customer. If you cancel your subscription, however, you lose your painstakingly compiled playlists.

Figure 1: In the web browser, Spotify runs the pay-to-listen music that the user previously compiled in their personal play list.
Figure 2: A Spotify playlist by the author on the iPhone.

Above the Clouds

Because the playlists reside in the provider's data center and not on my local machine, this left me with a slight feeling of unease. What would happen with my laboriously compiled playlists if Spotify were to fold? Thanks to the web API [4] that is also offered, I managed to save the data locally and overcome my fear of loss.

Via its web API, Spotify allows general catalog queries for music products without registering. For example, if you want to find out what the California band Weezer released on which albums, you can use a simple HTTP request as shown in Listing 1 [5]. The q (for query) parameter is set by the script to the name of the band; the type is set to track – this tells the server that the client is interested in tracks by the band in question.

Listing 1


01 #!/usr/local/bin/perl -w
02 use strict;
03 use LWP::UserAgent;
04 use JSON qw( from_json );
06 my $ua = LWP::UserAgent->new();
08 my $resp = $ua->get(
09     "" .
10     "q=weezer&type=track"
11 );
13 my $data = from_json( $resp->content() );
15 for my $item (
16       @{ $data->{ tracks }->{ items } } ) {
17     print "$item->{ name } ",
18           "($item->{ album }->{ name })\n";
19 }

The server sends back the results in JSON format; the from_json() method from the CPAN JSON module converts them into a nested hash data structure. The for loop from line 15 iterates over the array entries attached to the tracks-> items key and returns the music titles it found, as well as the album they are on. Figure 3 shows the output, which is limited to 20 entries but can be expanded with the API's paging mechanism.

Figure 3: Without registering, Spotify allows general searches, like the one shown here for tracks released by Weezer.

The script filters out the bulk of the information returned in JSON format. If you want, you can look out for the extra bits of information, like the popularity or play time, and additional details such as the release date of an album via links by dumping out everything to the screen.

And What's Your Favorite Music?

More interesting queries relate to the personal data of the Spotify user and require that user's consent. For example, to retrieve all playlists of a user, including the tracks, the requesting script needs to be registered as an application on the Spotify developer page [6], and it must identify itself with a valid OAuth token before Spotify releases the information. The instructions for application developers [7] describe the registration and handling of OAuth tokens step by step. However, Spotify only grants paying users access to the API.

Because I have presented several OAuth-controlled web APIs in this column  – for example, by Tumblr [8], Google Drive [9], or Dropbox [10]  – and have always used a Mojolicious script to obtain the first access token, it is about time that I wrote an extra CPAN module for this task: Scripts like the one shown in Listing 2 can henceforth use OAuth::Cmdline to start a web server and obtain the consent of the user in a docking browser. In spotify-token-init the two hex values in lines 9 and 10 accept the client identifier and client secret; the Spotify developer site hands these out to registered applications (Figures 4 and 5).

Listing 2


01 #!/usr/local/bin/perl -w
02 use strict;
03 use lib 'lib';
05 use OAuth::Cmdline;
06 use OAuth::Cmdline::Mojo;
08 my $oauth = OAuth::Cmdline->new(
09     client_id     => "XXX",
10     client_secret => "YYY",
11     login_uri     =>
12       "",
13     token_uri     =>
14       "",
15     site          => "spotify",
16     scope         => "user-read-private",
17 );
19 my $app = OAuth::Cmdline::Mojo->new(
20     oauth => $oauth,
21 );
23 $app->start( 'daemon', '-l', $oauth->local_uri );
Figure 4: After registering the web app …
Figure 5: … the client ID and the client secret appear.

Additionally, the script user states the URLs provided by Spotify for login and token renewal as login_uri and token_uri in the OAuth::Cmdline constructor. The extent of the permitted access is defined by the scope parameter, where user-read-private allows reading of private data. With write permission, scripts would be able to create playlists and add tracks to them.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • Spotify Comes to Linux

    Streaming music service comes to penguin users. Sorta.

  • Perl – Security Snapshots

    When the Perlmeister is on the road, he likes to know what's going on at home. Armed with just two scripts, he draws on the Tumblr API to store snapshots cyclically from his home security camera.

  • Perl: Google Drive

    Armed with a Chinese guillotine and a scanner with an automatic document feeder, Mike Schilli gives his books some special treatment, courtesy of Google Drive, which offers 5GB of storage space – room enough to start an online PDF collection.

  • Replace with VLC
comments powered by Disqus

Direct Download

Read full article as PDF:

Price $2.95


njobs Europe
Njobs Netherlands Njobs Deutschland Njobs United Kingdom Njobs Italia Njobs France Njobs Espana Njobs Poland
Njobs Austria Njobs Denmark Njobs Belgium Njobs Czech Republic Njobs Mexico Njobs India Njobs Colombia