Spotify | Music Discovery with Postman

We all love music. Love hearing it, making it, discovering it. Services like Pandora and Spotify have altered the way we satiate our need for discovering the next amazing song or artist.

A few years ago, Spotify introduced me to Neutral Milk Hotel. Their album, In the Aeroplane over the Sea was surreal, raw and honest. Today we’re going to make our own simplified version of the Discovery algorithm to identify similarly fervent music, using our beloved Postman app and Spotify’s fantastic API.

The objective is to generate a playlist with top songs from NMH (or an artist of your choosing), and other artists similar to it. Quickly jotting down the workflow:

  1. GET meta information about NMH using it’s Spotify ID
  2. GET the artists related to NMH
  3. Create a playlist named “Neutral Milk Hotel Mix”
  4. GET the most popular songs from NMH, choose a random 5 and add to the playlist
  5. For each related artist, do the same
  6. Et voila! A wonderful new mix!

Workflow:
0

At this point, anyone who wants to short circuit their way to the Playlist, click the Run in Postman button below to get the Collection and Environment file in your Postman app (versions 4.0 and above). Then follow the first 3 steps underneath.

Steps:

Get the artist ID from Spotify:

1

You get something like – spotify:artist:2ooIqOf4X2uz4mMptXCtie

2ooIqOf4X2uz4mMptXCtie is the artist id. Copy this inside your imported environment variable, as id.

Get the access token from Spotify

To not go beyond the scope of this discussion, I’ll keep auth simple and take the access token directly from Spotify’s Web Console.
Head to: https://developer.spotify.com/web-api/console/post-playlists and sign in. You’ll have to sign up as a developer account (A lot easier than it sounds)

2

Click on the Get OAuth Token button and grant the privileges as shown below:

3

Copy the access token in your environment under the authorization field.

Create/Update the Environment

If you used Run in Postman, update the imported environment, otherwise create a new Environment in Postman with the values as shown below:
a. id -> Artist ID from Step 1
b. country_code -> As outlined under available_markets in Spotify (https://developer.spotify.com/web-api/get-artists-top-tracks) – Defaulting to US
c. authorization -> AccessToken (from Step 2)
d. user_id -> Spotify username
e. N -> number of related songs and artists you want to add to the playlist

4v2

For the importers, jump to Step 5, else follow along!

Create Postman Collection

Create a new collection, named Spotify Playlist Generator, with the following requests:

a. Get Artist – As per the diagram above, the first request will GET the Artist’s metadate and store its name in the environment. We will use this to create the playlist name later.

5

URL: GET https://api.spotify.com/v1/artists/{{id}}
Headers:
i. Accept: application/json
ii. Authorization: Bearer {{authorization}}

Tests

tests["Status code is 200"] = (responseCode.code === 200);

if (responseCode.code === 200) {
    var artist = JSON.parse(responseBody);
    // Store the artist name in the environment
    postman.setEnvironmentVariable("artist_name", artist.name);
    // Store the artist id in an artists array
    postman.setEnvironmentVariable("artists", JSON.stringify([environment.id]));
    // As defined in the workflow, set the next request to be executed to Get Related Artists
    postman.setNextRequest("Get Related Artists");
    console.log("Information retrieved for artist: " + environment.artist_name);
}

postman.setNextRequest:
i. This function that allows non-linear execution of requests. As is evident from the name, you just need to specify the name of the subsequent request and the runner will take care of the rest.
ii. postman.setNextRequest is attached to a request and can be set in the pre-request or the test script. In case of more than one assignment, the final value is considered.
iii. The absence of postman.setNextRequest in the request’s pre-request or test scripts signals the end of workflow execution.
iv. If any request in the collection uses setNextRequest, the collection is considered to have a manual flow control, i.e. the normal linear execution is no longer honored.

So in the test script above, if the responseCode wasn’t 200, execution would stop.

b. Get Related Artists – I think I’d like a little randomness here, so we get a different playlist each time we run the collection. So let’s choose the N related artists randomly, instead of going for the most popular ones.

6

URL: GET https://api.spotify.com/v1/artists/{{id}}/related-artists
Headers:
i. Accept: application/json
ii. Authorization: Bearer {{authorization}}

Tests

tests["Status code is 200"] = (responseCode.code === 200);

if (responseCode.code === 200) {
    var n = _.parseInt(environment.N),
        relatedArtists = _(JSON.parse(responseBody).artists).sample(N).pluck('id').value(),
        artists = JSON.parse(environment.artists);

    artists = _.union(artists, relatedArtists);
    postman.setEnvironmentVariable("artists", JSON.stringify(artists));
    postman.setNextRequest("Create a Playlist");
    console.log("Related artists retrieved for: " + environment.artist_name);
}

c. Create a Playlist – Retrieve the name stored in the first request and create a playlist with the name “Artist_Name Mix”

7

URL: POST https://api.spotify.com/v1/artists/{{id}}/related-artists
Headers:
i. Accept: application/json
ii. Content-Type: application/json
iii. Authorization: Bearer {{authorization}}

Body:

{
  "name": "{{artist_name}} Mix",
  "public": false
}

Tests

tests["Status code is 201"] = (responseCode.code === 201);

if (responseCode.code === 201) {
    var playlist = JSON.parse(responseBody);

    // Store the playlist id in the environment to add tracks in the future
    postman.setEnvironmentVariable("playlist_id", playlist.id);
    postman.setNextRequest("Get Artist Top Tracks");
    console.log("Created playlist: " + environment.artist_name + " Mix");
}

d. Get Artist Top Tracks – Now we get into the fun part. We are going to loop through this and the next request N times (once per artist stored in the artists array). i.e. For each artist, get the top tracks and store them in the playlist.

8

URL: GET https://api.spotify.com/v1/artists/{{artist_id}}/top-tracks?country={{country_code}}
Headers:
i. Accept: application/json
ii. Authorization: Bearer {{authorization}}

Pre-request Script:

// Counter for the loop
var c = environment.c || 0;
var artists = JSON.parse(environment.artists);

// This value will be use in the URL
postman.setEnvironmentVariable("artist_id", artists[c]);

Tests

tests["Status code is 200"] = (responseCode.code === 200);

if (responseCode.code === 200) {
    var N = _.parseInt(environment.N),
        tracks = _(JSON.parse(responseBody).tracks).sample(N).pluck('id').value();

    // Store the track ids in the Environment, to be used in the next request
    postman.setEnvironmentVariable("tracks", JSON.stringify(tracks));
    postman.setNextRequest("Add Tracks to Playlist");
    console.log("Related artists retrieved for: " + environment.artist_name);
}

e. Add Tracks to Playlist – Add the track ids retrieved in the previous call, for the artist indexed at c, to the playlist (playlist_id)

9

URL: POST https://api.spotify.com/v1/users/{{user_id}}/playlists/{{playlist_id}}/tracks?uris={{uris}}
Headers:
i. Accept: application/json
ii. Content-Type: application/json
iii. Authorization: Bearer {{authorization}}

Pre-request Script:

var tracks = JSON.parse(environment.tracks);
// As required by Spotify API
var uris = _.map(tracks, function (track) {
        return "spotify:track:" + track;
    }).join(",");

postman.setEnvironmentVariable("uris", uris);

Tests

tests["Status code is 201"] = (responseCode.code === 201);

if (responseCode.code === 201) {
    var N = _.parseInt(environment.N);
    // Increment artist counter by 1
    var c = environment.c && (_.parseInt(environment.c) + 1) || 1;

    // If end of the loop, don’t setNextRequest
    if (c === N + 1) {
        postman.setEnvironmentVariable("c", 0);
        console.log("And we're done!");
    }
    // otherwise loop back to the previous request, to retrieve data for the next artist
    else {
        postman.setEnvironmentVariable("c", c);
        postman.setNextRequest("Get Artist Top Tracks");
        console.log("Moving to next artist's tracks");
    }
}

Run the Collection

Moment of truth! Now let’s run the collection and see if it works.

10

11

As you can see, the last 2 requests executed 6 times (1 for NMH and 5 for related artists)

And even Spotify has the playlist. Woohoo!

12

By the Way, the same collection executes in Newman as well. Just export the Collection and Environment files and execute the following command

newman -c SpotifyPLGen.json.postman_collection -e SpotifyPlGen.json.postman_environment

13

I hope you enjoyed this sneak preview into Postman Workflows. setNextRequest is just the beginning and we are working on more APIs to create increasingly complex workflows in the easiest possible manner in Postman. So stay tuned!

Comment

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.

2 thoughts on “Spotify | Music Discovery with Postman

    Hey!
    I am going along the article while watching your new Twitch stream (cool thing btw!) and I have noticed that the images in the article are miniatures only, when clicking it’s 404.
    Thanks for the article, cheers!

      We’re currently optimizing the blog, so I’ll let the team know – thanks!