2
votes

I'm new to working with APIs. I'm trying to create a script that will output the tracks of a public playlist from Spotify. I have hit a roadblock at an early stage: I'm unsure how exactly to format my GET request to retrieve the tracks of the playlist in question and where I put the OAuth access token. My current attempt returns a 401 status code.

What I've done so far:

  • I have created an App on the Spotify Developers website dashboard.
  • I have saved client_id and client_secret from the dashboard into a script ("spotifysecrets.py").
  • I have run the following code in my main script:
import requests

from spotifysecrets import client_id as cid, client_secret as cs

AUTH_URL = "https://accounts.spotify.com/api/token"

token_req = requests.post(AUTH_URL, {
    "grant_type": "client_credentials",
    "client_id": cid,
    "client_secret": cs
    })

access_token = token_req.json()["access_token"]

Everything appears to have worked fine so far. The problem occurs in the next step.

  • Having obtained the token, I am getting a 401 error when trying to make my tracks request. The code I have written is as follows:
pl_id = "…"  # I have elided the actual playlist ID for the purposes of this question
tracks = "https://api.spotify.com/v1/playlists/{}/tracks".format(pl_id)
songs_req = requests.get(tracks, {
    "Authorization": "Basic {}".format(access_token)
    })

Edit

I have tried using

songs_req = requests.get(tracks, headers={
    "Authorization": "Basic {}".format(access_token)
    })

instead but this gives a 400 error.

1

1 Answers

1
votes

I looked into the api and I believe you have a syntax error:

songs_req = requests.get(tracks, {
    "Authorization": "Basic {}".format(access_token)
    })

should be:

songs_req = requests.get(tracks, {
    "Authorization": "Bearer {}".format(access_token)
    })