Marek42
Marek42

Reputation: 51

Spotify Web API - How to play a playlist

I'm trying to get my hands on the Spotify API, but I don't know how to play a playlist or album. See my code below:

// Called when the Spotify Web Playback SDK is ready to use
window.onSpotifyWebPlaybackSDKReady = () => {  
  // Define the Spotify Connect device, getOAuthToken has an actual token
  // hardcoded for the sake of simplicity
  var player = new Spotify.Player({
    name: "A Spotify Web SDK Player",
    getOAuthToken: (callback) => {
      callback(
        "<Token to be placed here>"
      );
    },
    volume: 0.3,
  });

  // Called when connected to the player created beforehand successfully
  player.addListener("ready", ({ device_id }) => {
    console.log("Ready with Device ID", device_id);

    const play = ({
      context_uri,
      playerInstance: {
        _options: { getOAuthToken, id },
      },
    }) => {
      getOAuthToken((access_token) => {
        fetch(
          `https://api.spotify.com/v1/me/player/play?device_id=${device_id}`,
          {
            method: "PUT",
            body: JSON.stringify({ uris: [context_uri] }),
            headers: {
              "Content-Type": "application/json",
              Authorization: `Bearer ${access_token}`,
            },
          }
        );
      });
    };

    play({
      playerInstance: player,
      context_uri: "spotify:playlist:37i9dQZF1EIZKYrELNKNNT",
      position_ms: 0,
    });
  });

  // Connect to the player created beforehand, this is equivalent to
  // creating a new device which will be visible for Spotify Connect
  player.connect();
  console.log("playing?");
};

The actual problem is this part: context_uri: "spotify:playlist:37i9dQZF1EIZKYrELNKNNT

This will return 400 error:

{
  "error" : {
    "status" : 400,
    "message" : "Unsupported uri kind: playlist_v2"
  }
}

If I replace it with specific track uri, for instance spotify:track:72boGlgSwUK01n44O2tOCv everything works fine.

How can I pass a playlist uri instead of a specific track?

Upvotes: 3

Views: 1411

Answers (2)

Andrew Gremlich
Andrew Gremlich

Reputation: 473

In addition to what Crazy Unicorn posted, I found the details in the API documentation source.

In summary context_uri is for playing playlists and albums, and uris is for playing a collection of song URIs. They are in the body of the PUT request.

Upvotes: 0

Crazy Unicorn
Crazy Unicorn

Reputation: 11

I don't know if that would help you, but I had similar error and something like this worked for me:

data: JSON.stringify({ context_uri: context }),

Where "context" is a local variable of my AJAX method.

So it's basically the same as this:

data: JSON.stringify({ context_uri: "spotify:playlist:6SET13ADRq431RxMsMVlo4" }),

Upvotes: 1

Related Questions