Search code examples
pythonspotify

Spotify API, getting 404 as a response trying to find current song


Am trying to make a program that finds the current song playing and then to put it an one of my playlists. But am getting a 404 response when a trying to obtain the current playing song.

This is how I am getting my access token:

def get_token():
    auth_str = client_id + ":" + client_secret
    auth_bytes = auth_str.encode("utf-8")
    auth_base64 = str(base64.b64encode(auth_bytes), "utf-8")

    url = "https://accounts.spotify.com/api/token"
    headers = {
        "Authorization": "Basic " + auth_base64,
        "Content-Type": "application/x-www-form-urlencoded"
    }
    data = {"grant_type": "client_credentials"}
    result = post(url, headers=headers, data=data)
    json_result = json.loads(result.content)
    token = json_result["access_token"]
    return token

This is how I am creating the headers:

def get_headers(token):
    return {"Authorization": "Bearer " + token}

This is how I am trying to get the current playing song uri:

def get_current_track_and_post_in_playlist(token):
    headers = get_headers(token)
    result = get('https://api.spotify.com/v1/me/player/currently-playing', headers=headers)
    playlist_id = "0p4d0akcszc87kcf0pym6qws1"
    print(result)
    json_result = json.loads(result.content)["item"]["uri"]
    print(json_result)

    playlist_put = post(f'https://api.spotify.com/v1/playlists/{playlist_id}/tracks?uris={json_result}', headers=headers)

When am printing the result in get_current_track_and_post_in_playlist function i get a <Response [404]>. Can someone help me resolve this problem?


Solution

  • A reasons is required a user authentication for those two REST APIs.

    Get Currently Playing Track

    https://api.spotify.com/v1/me/player/currently-playing
    

    Add Items to Playlist

    https://api.spotify.com/v1/playlists/{playlist_id}/tracks
    

    It needs to get token by Authorization Code Flow

    So I will demo by local server with Flask

    This overall steps enter image description here

    # Step 1

    I play a song by browser. it will add into my playlist

    enter image description here

    # Step 2

    Running local redirect server with this code with add-song.py file name.

    You needs to config the Redirect URIs of your application in your dashboard.

    https://developer.spotify.com/dashboard/applications
    

    enter image description here

    from flask import Flask, request, redirect
    from requests_oauthlib import OAuth2Session
    from requests.auth import HTTPBasicAuth
    import requests
    import json
    
    app = Flask(__name__)
    
    AUTH_URL = 'https://accounts.spotify.com/authorize'
    TOKEN_URL = 'https://accounts.spotify.com/api/token'
    REDIRECT_URI = 'http://localhost:3000/callback' # your redirect URI
    CLIENT_ID = "<your client ID>"
    CLIENT_SECRET = "<your client Secret>"
    SCOPE = [
        "user-read-playback-state",
        "app-remote-control",
        "user-modify-playback-state",
        "playlist-read-private",
        "playlist-read-collaborative",
        "user-read-currently-playing",
        "user-read-playback-position",
        "user-library-modify",
        "playlist-modify-private",
        "playlist-modify-public",
        "user-read-recently-played",
        "user-read-private",
        "user-library-read"   
    ]
    
    def get_headers(token):
        return {"Authorization": "Bearer " + token}
    
    @app.route("/login")
    def login():
        spotify = OAuth2Session(CLIENT_ID, scope=SCOPE, redirect_uri=REDIRECT_URI)
        authorization_url, state = spotify.authorization_url(AUTH_URL)
        return redirect(authorization_url)
    
    # your redirect URI's path
    @app.route("/callback", methods=['GET'])
    def callback():
        code = request.args.get('code')
        res = requests.post(TOKEN_URL,
            auth=HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET),
            data={
                'grant_type': 'authorization_code',
                'code': code,
                'redirect_uri': REDIRECT_URI
            })
        access_token = res.json()['access_token']
        listObj = []
        listObj.append(res.json())
    
        # get current playing
        headers = get_headers(access_token)
        result1 = requests.get(url='https://api.spotify.com/v1/me/player/currently-playing', headers=headers)
        current_song = result1.json()
        listObj.append(current_song)
    
        # Add new song into playlist with current playing song
        playlist="<your playlist ID>"
        url = "https://api.spotify.com/v1/playlists/{0}/tracks".format(playlist)
        # current_song['item']['uri']  = 'spotify:track:xxxxxxxxxxxxxxxx'
        params = {'uris': current_song['item']['uri']}
        result2 = requests.post(url,
            params=params,
            headers={'Content-Type':'application/json',
                'Authorization': 'Bearer {0}'.format(access_token)})
        added_song = result2.json()    
        listObj.append(added_song)
        return listObj
    
    if __name__ == '__main__':
        app.run(port=3000,debug=True) # your redirect URI's port
    
    $ python add-song.py
    

    #3 Login by Browser

    http://localhost:3000/login
    

    login your Spotify credential enter image description here

    Before add Song enter image description here

    After added Song enter image description here

    In the browser, will display current play song information and added song's snapshot_id. enter image description here

    The key is playing song's track URI needs to set a parameter of add playlist.

    current_song['item']['uri']
    

    #Step 4~6

    It is running by inside code.

    I hope to this demo your are looking for solution.