[GH-ISSUE #693] 127.0.0.1 sent an invalid response. ERR_SSL_PROTOCOL #410

Closed
opened 2026-02-27 23:22:28 +03:00 by kerem · 5 comments
Owner

Originally created by @Srijha09 on GitHub (Jun 22, 2021).
Original GitHub issue: https://github.com/spotipy-dev/spotipy/issues/693

I am sort of new to APIs and trying to get myself accustomed with Spotify API with a Flask application. I was able to authenticate with the Spotify Authentication but instead of going to the index.html page I got an ERR_SSL_PROTOCOL error.
image
I am not able to figure out what went wrong. I gave the correct credentials (client_id, secret), valid redirect URI .
It would be appreciated if someone can help me out on this.

I also tried changing the client_url http://127.0.0.1:5000/callback/q to https://127.0.0.1:5000/callback/q. Just in case that caused the error. Yet ERR_SSL_PROTOCOL error persists

Thanks!

Originally created by @Srijha09 on GitHub (Jun 22, 2021). Original GitHub issue: https://github.com/spotipy-dev/spotipy/issues/693 I am sort of new to APIs and trying to get myself accustomed with Spotify API with a Flask application. I was able to authenticate with the Spotify Authentication but instead of going to the index.html page I got an ERR_SSL_PROTOCOL error. ![image](https://user-images.githubusercontent.com/50697493/122972416-cc3d6f00-d398-11eb-8215-a25831387f58.png) I am not able to figure out what went wrong. I gave the correct credentials (client_id, secret), valid redirect URI . It would be appreciated if someone can help me out on this. I also tried changing the client_url http://127.0.0.1:5000/callback/q to https://127.0.0.1:5000/callback/q. Just in case that caused the error. Yet ERR_SSL_PROTOCOL error persists Thanks!
kerem closed this issue 2026-02-27 23:22:28 +03:00
Author
Owner

@Peter-Schorn commented on GitHub (Jun 22, 2021):

Please post the code for your web app and the full URL of the page that is shown in the screenshot above.

<!-- gh-comment-id:866214096 --> @Peter-Schorn commented on GitHub (Jun 22, 2021): Please post the code for your web app and the full URL of the page that is shown in the screenshot above.
Author
Owner

@Srijha09 commented on GitHub (Jun 22, 2021):

spotify_client.py

` import json
import requests
from urllib.parse import quote

class SpotifyClient:
# Spotify API URLS
API_VERSION = "v1"
SPOTIFY_AUTH_URL = "https://accounts.spotify.com/authorize"
SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token"
SPOTIFY_API_BASE_URL = "https://api.spotify.com"
SPOTIFY_API_URL = f"{SPOTIFY_API_BASE_URL}/{API_VERSION}"

#Server-side parameters
STATE = ""
SHOW_DIALOG_bool = True
SHOW_DIALOG_str = str(SHOW_DIALOG_bool).lower()
SCOPE = "playlist-modify-public playlist-modify-private playlist-read-private user-read-recently-played"

CLIENT_SIDE_URL = 'https://127.0.0.1'

def __init__(self, client_id, client_secret, client_side_url=CLIENT_SIDE_URL, port=None):
    self.client_id = client_id
    self.client_secret = client_secret
    self.client_side_url = client_side_url
    self.port = port
    self._access_token = ''
    self.authorization_header = ''
    self.redirect_uri = f"{self.client_side_url}/callback/q" if port is None else f"{self.client_side_url}:{self.port}/callback/q"

def get_auth_url(self):
    auth_query_parameters = {
        "response_type": "code",
        "redirect_uri": self.redirect_uri,
        "scope": self.SCOPE,
        "show_dialog": self.SHOW_DIALOG_str,
        "client_id": self.client_id
        #"state": STATE,
    }

    url_args = "&".join([f"{key}={quote(str(val))}" for key, val in auth_query_parameters.items()])
    return f"{self.SPOTIFY_AUTH_URL}/?{url_args}"

def get_authorization(self, auth_token):
    """
    returning authorization data and setting the authorization_header
    :param auth_token:
    :return: dict
    """

    data = {
        "grant_type": "authorization_code",
        "code": str(auth_token),
        "redirect_uri": self.redirect_uri,
        'client_id': self.client_id,
        'client_secret': self.client_secret,
    }
    post_request = requests.post(self.SPOTIFY_TOKEN_URL, data=data)

    response_data = json.loads(post_request.text)
    self._access_token = response_data["access_token"]
    self.authorization_header = {"Authorization": f"Bearer {self._access_token}"}

    return dict(
        access_token=response_data["access_token"],
        refresh_token=response_data["refresh_token"],
        token_type=response_data["token_type"],
        expires_in=response_data["expires_in"],
    )

def get_user_profile_data(self, auth_header):
    """Getting user data 
    auth_header: the authentication header
    """
    user_profile_api_endpoint = f"{self.SPOTIFY_API_URL}/me"
    profile_data = requests.get(user_profile_api_endpoint, headers=auth_header).text
    return json.loads(profile_data)

def get_user_last_played_tracks(self, auth_header, user_id, limit=25):
    """Get the last n tracks played by a user who logins
    :param auth_header: the authentication header
    :param user_id: the Spotify User ID when a user gets authenticated in Spotify
    :param limit: Number of tracks to get. Limit should be <= 50
    :return : List of last played n tracks from the user
    """
    last_played_api_endpoint = f"https://api.spotify.com/v1/users/{user_id}/player/recently-played?limit={limit}"
    tracks = json.loads(requests.get(last_played_api_endpoint, headers=auth_header).text)
    tracks = tracks['items']

    return [
         {
            'track_artist': track['track']['artists'][0]['name'],
            'track_name': track['track']['name'],
            'track_image': track['track']['album']['images'][0]['url'],
            'track_url': track['track']['external_urls']['spotify'],
            'track_id': track['track']['id']
         } for track in tracks
    ] `

app.py
` #Flask imports
from flask import Flask,Blueprint,request, url_for, session, redirect, render_template
#script imports
from helper.spotifyclient import SpotifyClient
#spotify imports
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import time
import config
import json
import requests

app = Flask(name)

app.secret_key = "rhythmify"
app.config['SESSION_COOKIE_NAME'] = "Rhythmify Cookie"
app.config['TEMPLATES_AUTO_RELOAD'] = True
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0
TOKEN_INFO = "token_info"
client_id = config.SPOTIFY_CLIENT_ID
client_secret = config.SPOTIFY_CLIENT_SECRET
app.config['all_sp_objects'] = {}
#---------------------------------HOME PAGE-----------------------------------------
spotify_client = SpotifyClient(client_id, client_secret, port=5000)
@app.route("/", methods=['POST', 'GET'])
def login():
"""
redirect to Spotify's log in page
"""
auth_url = spotify_client.get_auth_url()
return redirect(auth_url)

@app.route("/callback/q")
def callback():
"""
set the session's authorization header
"""
auth_token = request.args['code']
spotify_client.get_authorization(auth_token)
authorization_header = spotify_client.authorization_header
session['authorization_header'] = authorization_header
return redirect(url_for("home"))

@app.route("/home")
def home():
render_template('index.html') `

Screenshot (2)

URL of Screenshot:
https://127.0.0.1:5000/callback/q?code=AQAI_8m09DYhA2yfmaQTvw4Ig5x0nkkz4B2QppXaCfjyLPnrLXBep2D68mkpodFjw2o7tSy1yGhbRn75uq3n-sZJIL8ZfjspIE7Zf0jo75RhO-kaCoqYhHLdpN2tvoieRf38REthFgsSmi1VaHJdAP0UUta4a3_jQAZDRKQa8RP-jTeMUyIXR9VfMXFjOA77mR6UtB1Wgk5gKyf6eI4xKJl8PM4zpU_uIaK2Dpyc-_9z3j56mCP0DRcER0YiuXzwSoze155u7evzjrd17MjeUZEe6-uk_LykVvA0yCRUCAJcFIsDaXBHew

<!-- gh-comment-id:866231731 --> @Srijha09 commented on GitHub (Jun 22, 2021): **spotify_client.py** ` import json import requests from urllib.parse import quote class SpotifyClient: # Spotify API URLS API_VERSION = "v1" SPOTIFY_AUTH_URL = "https://accounts.spotify.com/authorize" SPOTIFY_TOKEN_URL = "https://accounts.spotify.com/api/token" SPOTIFY_API_BASE_URL = "https://api.spotify.com" SPOTIFY_API_URL = f"{SPOTIFY_API_BASE_URL}/{API_VERSION}" #Server-side parameters STATE = "" SHOW_DIALOG_bool = True SHOW_DIALOG_str = str(SHOW_DIALOG_bool).lower() SCOPE = "playlist-modify-public playlist-modify-private playlist-read-private user-read-recently-played" CLIENT_SIDE_URL = 'https://127.0.0.1' def __init__(self, client_id, client_secret, client_side_url=CLIENT_SIDE_URL, port=None): self.client_id = client_id self.client_secret = client_secret self.client_side_url = client_side_url self.port = port self._access_token = '' self.authorization_header = '' self.redirect_uri = f"{self.client_side_url}/callback/q" if port is None else f"{self.client_side_url}:{self.port}/callback/q" def get_auth_url(self): auth_query_parameters = { "response_type": "code", "redirect_uri": self.redirect_uri, "scope": self.SCOPE, "show_dialog": self.SHOW_DIALOG_str, "client_id": self.client_id #"state": STATE, } url_args = "&".join([f"{key}={quote(str(val))}" for key, val in auth_query_parameters.items()]) return f"{self.SPOTIFY_AUTH_URL}/?{url_args}" def get_authorization(self, auth_token): """ returning authorization data and setting the authorization_header :param auth_token: :return: dict """ data = { "grant_type": "authorization_code", "code": str(auth_token), "redirect_uri": self.redirect_uri, 'client_id': self.client_id, 'client_secret': self.client_secret, } post_request = requests.post(self.SPOTIFY_TOKEN_URL, data=data) response_data = json.loads(post_request.text) self._access_token = response_data["access_token"] self.authorization_header = {"Authorization": f"Bearer {self._access_token}"} return dict( access_token=response_data["access_token"], refresh_token=response_data["refresh_token"], token_type=response_data["token_type"], expires_in=response_data["expires_in"], ) def get_user_profile_data(self, auth_header): """Getting user data auth_header: the authentication header """ user_profile_api_endpoint = f"{self.SPOTIFY_API_URL}/me" profile_data = requests.get(user_profile_api_endpoint, headers=auth_header).text return json.loads(profile_data) def get_user_last_played_tracks(self, auth_header, user_id, limit=25): """Get the last n tracks played by a user who logins :param auth_header: the authentication header :param user_id: the Spotify User ID when a user gets authenticated in Spotify :param limit: Number of tracks to get. Limit should be <= 50 :return : List of last played n tracks from the user """ last_played_api_endpoint = f"https://api.spotify.com/v1/users/{user_id}/player/recently-played?limit={limit}" tracks = json.loads(requests.get(last_played_api_endpoint, headers=auth_header).text) tracks = tracks['items'] return [ { 'track_artist': track['track']['artists'][0]['name'], 'track_name': track['track']['name'], 'track_image': track['track']['album']['images'][0]['url'], 'track_url': track['track']['external_urls']['spotify'], 'track_id': track['track']['id'] } for track in tracks ] ` **app.py** ` #Flask imports from flask import Flask,Blueprint,request, url_for, session, redirect, render_template #script imports from helper.spotifyclient import SpotifyClient #spotify imports import spotipy from spotipy.oauth2 import SpotifyOAuth import time import config import json import requests app = Flask(__name__) app.secret_key = "rhythmify" app.config['SESSION_COOKIE_NAME'] = "Rhythmify Cookie" app.config['TEMPLATES_AUTO_RELOAD'] = True app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 TOKEN_INFO = "token_info" client_id = config.SPOTIFY_CLIENT_ID client_secret = config.SPOTIFY_CLIENT_SECRET app.config['all_sp_objects'] = {} #---------------------------------HOME PAGE----------------------------------------- spotify_client = SpotifyClient(client_id, client_secret, port=5000) @app.route("/", methods=['POST', 'GET']) def login(): """ redirect to Spotify's log in page """ auth_url = spotify_client.get_auth_url() return redirect(auth_url) @app.route("/callback/q") def callback(): """ set the session's authorization header """ auth_token = request.args['code'] spotify_client.get_authorization(auth_token) authorization_header = spotify_client.authorization_header session['authorization_header'] = authorization_header return redirect(url_for("home")) @app.route("/home") def home(): render_template('index.html') ` ![Screenshot (2)](https://user-images.githubusercontent.com/50697493/122979920-c51a5f00-d3a0-11eb-9435-354180b712d6.png) **URL of Screenshot:** https://127.0.0.1:5000/callback/q?code=AQAI_8m09DYhA2yfmaQTvw4Ig5x0nkkz4B2QppXaCfjyLPnrLXBep2D68mkpodFjw2o7tSy1yGhbRn75uq3n-sZJIL8ZfjspIE7Zf0jo75RhO-kaCoqYhHLdpN2tvoieRf38REthFgsSmi1VaHJdAP0UUta4a3_jQAZDRKQa8RP-jTeMUyIXR9VfMXFjOA77mR6UtB1Wgk5gKyf6eI4xKJl8PM4zpU_uIaK2Dpyc-_9z3j56mCP0DRcER0YiuXzwSoze155u7evzjrd17MjeUZEe6-uk_LykVvA0yCRUCAJcFIsDaXBHew
Author
Owner

@stephanebruckert commented on GitHub (Jun 22, 2021):

I see you are visiting https instead of http! When working locally, make sure you visit http://127.0.0.1:5000

<!-- gh-comment-id:866233570 --> @stephanebruckert commented on GitHub (Jun 22, 2021): I see you are visiting https instead of http! When working locally, make sure you visit http://127.0.0.1:5000
Author
Owner

@Srijha09 commented on GitHub (Jun 22, 2021):

Alright thanks alot!

<!-- gh-comment-id:866256745 --> @Srijha09 commented on GitHub (Jun 22, 2021): Alright thanks alot!
Author
Owner

@IgorAguiar-Giro commented on GitHub (Jan 4, 2024):

I wish my problem was that simple XD

<!-- gh-comment-id:1877728235 --> @IgorAguiar-Giro commented on GitHub (Jan 4, 2024): I wish my problem was that simple XD
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
starred/spotipy#410
No description provided.