My goal is to connect to the Spotify API using pure Python and I have been able to figure out how to obtain the authorization token given the authorization code but I am unable to get the authorization code itself.
Note: I have not provided the client_id and client_secret for obvious reasons and you can assume that all libraries have been imported.
Once the web browser opens, the authorization code ("code") is displayed as a query parameter in the URL but I am unsure how to go about saving it to a variable. I can't just copy and paste it to a variable as the authorization code constantly changes.
My question is how exactly I would go about retrieving the code query paramter and save it to a variable?
Here is what I have tried so far:
# credentials
client_id = "xxx..."
client_secret = "xxx..."
# urls
redirect_uri = "http://localhost:7777/callback"
auth_url = "https://accounts.spotify.com/authorize?"
token_url = "https://accounts.spotify.com/api/token"
# data scopes
scopes = "user-read-private user-read-email"
# obtains authorization code
payload = {
"client_id": client_id,
"response_type": "code",
"redirect_uri": redirect_uri,
"scope": scopes
}
webbrowser.open(auth_url + urlencode(payload))
code = # NOT SURE HOW TO RETRIEVE CODE
# obtains authorization token
encoded_creds = base64.b64encode(client_id.encode() + b":" + client_secret.encode()).decode('utf-8')
token_headers = {
"Authorization": "Basic " + encoded_creds,
"Content-Type": "application/x-www-form-urlencoded"
}
token_data = {
"grant_type": "authorization_code",
"code": code,
"redirect_uri": redirect_uri
}
r = req.post(token_url, data=token_data, headers=token_headers)
auth_url? If so, is the auth code you want in the response somewhere? If it is, then it shouldn't be hard to extract it so that you can use it in your second request. If it's not there, what IS there? Are you asking what additional requests you need to make to get the auth code?