Announcements

Help Wizard

Step 1

NEXT STEP

Add Track to Playlist

Add Track to Playlist

Hello everyone, 

 

i am trying to add some tracks to a spotify playlist of mine. But I always get the error Error: 401 Client Error: Unauthorized for url. Can someone help? Thank you 🙂

 

This is my code:

 

def get_auth_header(token😞
    return {"Authorization": "Bearer " + token}
def get_token():
    auth_string = CLIENT_ID + ":" + CLIENT_SECRET
    auth_bytes = auth_string.encode("utf-8")
    auth_base64 = str(base64.b64encode(auth_bytes), "utf-8")

    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

def add_tracks_to_playlist(access_token, playlist_id, uris, position=None😞
    """
    Add tracks to a Spotify playlist.

    Parameters:
        access_token (str): The access token for Spotify API.
        playlist_id (str): The Spotify ID of the playlist.
        uris (list of str): A list of Spotify URIs to add.
        position (int, optional): The position to insert the items. If omitted, the items will be appended to the playlist.

    Returns:
        response (dict): The response from Spotify API.
    """
    url = f"https://api.spotify.com/v1/playlists/{playlist_id}/tracks"
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json"
    }
    data = {
        "uris": uris
    }
    if position is not None:
        data["position"] = position

    response = requests.post(url, headers=headers, json=data)

    if response.status_code == 201:
        return response.json()
    else:
        response.raise_for_status()

if __name__ == "__main__":
    # Replace these values with your own
    ACCESS_TOKEN = get_token()

    PLAYLIST_ID = "ID"
    URIS = [
        "spotify:track:4iV5W9uYEdYUVa79Axb7Rh",
        "spotify:track:1301WleyT98MSxVHPZCA6M",
        "spotify:episode:512ojhOuo1ktJprKbVcKyQ"
    ]
    POSITION = 0  # Optional

    try:
        result = add_tracks_to_playlist(ACCESS_TOKEN, PLAYLIST_ID, URIS, POSITION)
        print("Tracks added successfully!")
        print("Snapshot ID:", result["snapshot_id"])
    except requests.exceptions.HTTPError as err:
        print(f"Error: {err}")
Reply
1 Reply

You can use Client Credentials for this, and should use the Authorization Code with PKCE Flow.

Don't forget to the Authorization scopes playlist-modify-public and playlist-modify-private, as mentioned here.

XimzendSpotify Star
Help others find this answer and click "Accept as Solution".
If you appreciate my answer, maybe give me a Like.
Note: I'm not a Spotify employee.

Suggested posts

Let's introduce ourselves!

Hey there you,   Yeah, you! 😁   Welcome - we're glad you joined the Spotify Community!   While you here, let's have a fun game and get…

ModeratorStaff / Moderator/ 4 years ago  in Social & Random