Gabriel Zangerme
Gabriel Zangerme

Reputation: 95

Only valid bearer authentication supported - Python - Spotify API

I was coding this script that can get into my liked videos and make a playlist on Spotify with the title and artist of each video.

I already tried to renew the Token from the Spotify API manager, but for some reason it's still showing the following error:

  status': 400, 'message': 'Only valid bearer authentication supported'}}
Traceback (most recent call last):
  File "/Users/gzangerme/Desktop/Python Project/SpotifyAutomation.py", line 159, in <module>
    cp.add_song_to_playlist()
  File "/Users/gzangerme/Desktop/Python Project/SpotifyAutomation.py", line 129, in add_song_to_playlist
    self.get_liked_videos()
  File "/Users/gzangerme/Desktop/Python Project/SpotifyAutomation.py", line 76, in get_liked_videos
    "spotify_uri": self.get_spotify_uri(song_name, artist)
  File "/Users/gzangerme/Desktop/Python Project/SpotifyAutomation.py", line 119, in get_spotify_uri
    songs = response_json["tracks"]["items"]
KeyError: 'tracks'

I noticed that the KeyError is showing up because the call is returning an error.

Here follows the code for the project:

import json
import requests
import os
from secrets import spotify_user_id, spotify_token
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
import youtube_dl



class CreatePlaylist:

    def __init__(self):
        self.user_id = spotify_user_id
        self.spotify_token = spotify_token
        self.youtube_client = self.get_youtube_client()
        self.all_song_info = {}

    #Step 1
    def get_youtube_client(self):
        os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

        api_service_name = "youtube"
        api_version = "v3"

        #Get Credentials for API Client
        flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file('client_secret.json', scopes=['https://www.googleapis.com/auth/youtube'])
        credentials = flow.run_console()
        youtube_client = googleapiclient.discovery.build(api_service_name, api_version, credentials=credentials)

        return youtube_client

    #Step 2
    def get_liked_video(self):
        request = self.youtube_client.videos().list(
            part="snippet,contentDetails,statistics",
            myRating="Like"
        )
        response = request.execute()

        #Get information on each video on the list
        for item in response["items"]:
            video_title = item["snippet"]["title"]
            youtube_url = "https://www.youtube.com/watch?v={}".format(item["id"])
            #use youtube_dl to colect the name of the song and the artist

            video = youtube_dl.YoutubeDL({}).extract_info(youtube_url,download = False)
            song_name = video["track"]
            artist = video["artist"]

            self.all_song_info[video_title] = {
                "youtube_url":youtube_url,
                "song_name":song_name,
                "artist":artist,
                "spotify_uri":self.get_spotify_uri(song_name,artist)
            }

    #Step 3
    def create_playlist(self):
        request_body = json.dumps({
            "name":"Youtube Liked Videos",
            "description":"Todos os Videos com Like do YT",
            "public": True
        })
        query = "https://api.spotify.com/v1/users/{user_id}/playlists".format()
        response = requests.post(
            query,
            data= request_body,
            headers={
                "Content-type": "application/json",
                "Authorization": "Bearer {}".format(spotify_token)
            }
        )
        response_json = response.json

        #playlistId
        return response_json["id"]

    #Step 4
    def get_spotify_uri(self, song_name, artist):
        query = "https://api.spotify.com/v1/search".format(
        song_name, 
        artist
        )
        response = requests.get(
            query,
            headers={
                "Content-type": "application/json",
                "Authorization": "Bearer {}".format(spotify_token)
            }
        )
        response_json = response.json()
        songs = response_json["tracks"]["items"]

        #configurar para utilizar somente a primeira musica
        uri = songs[0]["uri"]
        return uri

    #Step 5
    def add_song_to_playlist(self):

        self.get_liked_video()

        uris = []
        for song ,info in self.all_song_info():
            uris.apend(info["spotify_uri"])

        #create new playlist
        playlist_id = self.create_playlist

        #add musics to the created playlist
        request_data = json.dumps(uris)

        query = "https://api.spotify.com/v1/playlists/{playlist_id}/tracks".format(playlist_id)

        response = requests.post(
            query,
            data=request_data,
            headers = {
                "Content-Type":"application/json",
                "Authorization": "Bearer {}".format(self.spotify_token)              
            }
        )

        response_json = response.json()
        return response_json


CreatePlaylist()

Upvotes: 1

Views: 1198

Answers (1)

Chris
Chris

Reputation: 56

I think the spotify_token and spotify_user_id are the issue. If you go to: https://pypi.org/project/spotify-token/ it is a Python script where you can generate a Spotify token.

As for the spotify_user_id that is your username on Spotify. To find your username, go to: https://www.spotify.com/us/ , click on Profile > Account > Account overview

Hope it helps.

Upvotes: 1

Related Questions