'Spotipy - Validating successful authentication

I was wondering how to validate that a user has correctly entered their spotify developer profile information correctly. I have a file, credentials.py, with 3 constants needed to get a spotify API token. In main.py, I use these constants like so.

def authenticate_user():
    if not credentials.SPOTIPY_CLIENT_SECRET or not credentials.SPOTIPY_CLIENT_ID:
        raise RuntimeError("Spotify credentials have not been set! Check credentials.py")

    os.environ["SPOTIPY_CLIENT_ID"] = credentials.SPOTIPY_CLIENT_ID
    os.environ["SPOTIPY_CLIENT_SECRET"] = credentials.SPOTIPY_CLIENT_SECRET
    os.environ["SPOTIPY_REDIRECT_URI"] = credentials.SPOTIPY_REDIRECT_URI

    sp = spotipy.Spotify(auth_manager=spotipy.SpotifyOAuth())
    return sp

The resulting variable, sp, does not seem to have any methods to verify that it has successfully been validated. On attempting to use any methods, you are sent to a webpage with the corresponding spotify endpoint, showing that the request failed. When exiting the page, no error is thrown and the program hangs. How do I throw an error on invalid information being used to authenticate with the spotify servers?



Solution 1:[1]

You can check if the spotipy api returns a boolean upon verification, just make an if statement that looks like this:

If (sp == True):
  Print('credentials valid')

Solution 2:[2]

Base on Spotify docs here

you should get a Spotify.oauth2.SpotifyOauthError then you can surround the code with a try and except.

you can do it like this:

try:
    sp = spotipy.Spotify(auth_manager=spotipy.SpotifyOAuth())
    return sp
except SpotifyOauthError as e:
    raise RuntimeError(f"Spotify credentials didn't work, error={e}")

just don't forget to import the exception from Spotify.oauth2.SpotifyOauthError

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jan Arend
Solution 2