Spotipy (Spotify's Web API Python wrapper) examples failing - python

I cloned and installed Paul Lamere's Python wrapper for the Spotify Web API via python setup.py install but I can't seem to run some of the examples correctly.
Specifically, when I try to run user_playlists_contents.py or user_starred_playlist.py, a browser is launched and I'm directed to the Spotify login page. After logging in, I get a Spotify error within the browser that only says: "Oops! Something went wrong." The script asks for the URL I was redirected to, but entering in both the URL of the login page and the URL of the error page (obviously) trigger an error within the Terminal: spotipy.oauth2.SpotifyOauthError: Bad Request
At first I was using a Facebook-connected Spotify account and logging in to Spotify through Facebook when prompted, so I thought that might be an issue. However even after creating a new email-only Spotify account and running the scripts on this new email-only username I got the same results.
I also tried registering a new App in my Spotify developer account and using its CLIENT_ID, CLIENT_SECRET, and REDIRECT_URI in the examples/util.py but this didn't seem to do anything. It seems unlikely anyways that modifying examples/util.py is necessary.
Thinking this might be a browser issue I also reset my browser (Chrome) and after that didn't work I tried switching Safari to the default browser but that also did nothing.
Both these scripts depend on prompt_for_user_token() which is defined in examples/util.py, and seems to be where things are going wrong.
What am I doing wrong? Have I missed something painfully obvious? Thanks in advance.

prompt_for_user_token method looks as below:
def prompt_for_user_token(username, scope=None):
''' prompts the user to login if necessary and returns
the user token suitable for use with the spotipy.Spotify
constructor
'''
client_id = os.getenv('CLIENT_ID', 'YOUR_CLIENT_ID')
client_secret = os.getenv('CLIENT_SECRET', 'YOUR_CLIENT_SECRET')
redirect_uri = os.getenv('REDIRECT_URI', 'YOUR_REDIRECT_URI')
.
.
which requires you to set CLIENT_ID, CLIENT_SECRET and REDIRECT_URI environment variables before executing the example. You get these values by creating an app at My Applications section of Spotify Developer Site
In Unix, you can set environment variables in the command line as follows:
export CLIENT_ID={yourclient}
export CLIENT_SECRET={yoursecret}
export REDIRECT_URI={your redirect uri}
Then you need to copy and paste the full url you were redirected to on browser to proceed.

I have a similar problem and found at least a work around solution. See here. I got this to work by passing the client_id, client_secret, redirect_uri as agruments in util.prompt_for_user_token. I had to copy and paste the entire URL including code. I did not mess with util.py at all.

Related

How can I allow my program permanent authorization for one spotify account (my own) with the spotify api?

I am building a local desktop app where I can read, classify, and create playlists.
The following auth code I have is:
##oauth
scope = "playlist-modify-public playlist-read-private playlist-modify-private"
sp = spotipy.Spotify(
auth_manager=spotipy.SpotifyOAuth(
client_id=client_id,
client_secret=client_secret,
redirect_uri= "https://example.com/callback/",
scope= scope, open_browser=False))
when run on cmd, this asks to click the link generated and then to paste the link that I was redirected to. I want to know if there is another way to provide authorization (automatically or permanently) so that my .exe app doesn't run into an error.
code in your response would help a lot.
You cannot grant permanent access to the APIs in a single call, but you can refresh your token automatically whenever the access expires, as shown in the docs.
If you're using Python, I recommend to do this via Spotipy, which makes the auth process much easier (see https://spotipy.readthedocs.io/en/master/#authorization-code-flow)

Persistent issues with Spotify Web API redirect URI

I know this has been posted about multiple times but I've tried all the solutions I've found on SO and none have worked. I'm trying to retrieve user data about myself from Spotify's Web API by following simple examples like the ones posted here and here. So I've now tried both Spotify and tekore but neither are working for me.
The closest I've come to making it work is by following this example. When I run that code in a Jupyter Notebook, a separate window pops open and prompts me to agree to authorize access to my data. When I select "Agree" I get an "ERR_TOO_MANY_REDIRECTS" error and the suggestion to clear my cookies, which I've done multiple times now.
And when I enter my redirect URI in the prompt that pops up in the notebook, I get the following error: "KeyError: 'Passed URL contains no parameter code!'"
I am using "http://localhost:8888/callback/" as the redirect URI and I've double-checked to make sure the whitelisted URI matches what I'm using in my notebook. Any suggestions as to what I'm doing wrong?
Lastly, here's the code I'm trying:
import tekore as tk
# Read in keys
client_id = open('./spotify-client-id.txt', 'r').read().rstrip('\n')
client_secret = open('./spotify-client-secret.txt', 'r').read().rstrip('\n')
# Set URI
redirect_uri = 'http://localhost:8888/callback/'
conf = (client_id, client_secret, redirect_uri)
token = tk.prompt_for_user_token(*conf, scope=tk.scope.every)
spotify = tk.Spotify(token)
tracks = spotify.current_user_top_tracks(limit=10)
spotify.playback_start_tracks([t.id for t in tracks.items])
Apparently the trick is to ignore the error message, copy the URL from the browser, and paste it into the cell in your Jupyter Notebook.
spotipy should cache the response so that you don't have to go through this process each time. Thanks to murraypaul on Spotify's Community help forum for this advice.

Gaining authorization to modify Spotify playlists using spotipy for Python3

I'm currently attempting to use spotipy, a python3 module, to access and edit my personal Spotify premium account. I've followed the tutorial on https://github.com/plamere/spotipy/blob/master/docs/index.rst using the util.prompt_for_user_token method by entering the necessary parameters directly (username, client ID, secret ID, scope and redirect uri). Everything seems to be fine up to this part. My code (fillers for username, client id and client secret for security reasons) :
code
It opens up my default web browser and redirects me to my redirect url with the code in it. At this point, I copy and paste the redirect url (as prompted) and hit enter. It returns the following error:
Error
My redirect uri is 'http://google.com/' for this specific example. However, I've tried multiple redirect uris but they all seem to produce the same error for me. (and yes, I did set my redirect uri as whitespace for my application). I've spent hours trying to fix this issue by looking at online tutorials, trying different redirect urls, changing my code but have yet to make any progress. I'm hoping I am just overlooking a simple mistake here! Any feedback on how to fix this is much appreciated!
If it matters: I'm using the IDE PyCharm.
I had to use two different solutions to deal with the redirect_uri issue depending on which IDE I was using. For Jupyter Lab/Notebook, I could use a localhost for the redirect_url
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id="your_client_id", client_secret="your_client_secret", redirect_uri="https://localhost:8890/callback/", scope="user-library-read"))
For Google Colab, I had to use a publicly accessible website. I think "https://google.com/" should work but I used my band's website so I'd remember that the redirect_uri had to match the one in your Spotify Develop dashboard settings.
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id="your_client_id", client_secret="your_client_secret", redirect_uri="https://yourwebsite.com/", scope="user-library-read"))
I just ended up using my bands website because it was easier for me to remember. Make sure to go to the Spotify developer dashboard (https://developer.spotify.com/dashboard/applications) and match the redirect_uri with what you are planning to use at that time.
I think it is your redirect URL - working for me with:
import os
import spotipy.util as util
# credentials
user = 'username'
desired_scope = 'playlist-modify-private'
id = os.environ.get('SPOT_CLIENT')
secret = os.environ.get('SPOT_SECRET')
uri = 'https://localhost'
token = util.prompt_for_user_token(username=user,
scope=desired_scope,
client_id=id,
client_secret=secret,
redirect_uri=uri)
I think for your redirect url spotify requires the initial http(s) part - don't forget to add it to the white-list in your Spotify for Developers app too, as otherwise you will get 'invalid-redirect-uri'.

GData and OAuth in Python: Unable to convert request token to access token

I am trying to implement a button on a web-based dashboard that allows a user to export the current data to a Google Spreadsheet using OAuth and GData API. Currently, I can get the user to a login/grant access page, but if I add the line to convert the request token to an access token, I receive:
"RequestError: Unable to upgrade OAuth request token to access token: 400, parameter_absent
oauth_parameters_absent:oauth_token"
I am following the instructions for OAuth 2 on this page:
https://developers.google.com/gdata/docs/auth/oauth
and have read both PyDocs for the Google APIs and found no details on this issue:
http://gdata-python-client.googlecode.com/hg/pydocs/gdata.docs.client.html#DocsClient
(Won't let me post a this hyperlink but other Pydoc is same URL but replace the piece after pydocs/ with gdata.gauth.html#ClientLoginToken)
This is the code that works:
def createDocsClient(self, oauth_callback_url):
docsClient = gdata.docs.client.DocsClient(source='RiskOps-QualityDashboard')
request_token = docsClient.GetOAuthToken(SCOPES, oauth_callback_url, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET)
domain = None
auth_url = request_token.generate_authorization_url(google_apps_domain=domain)
self.redirect(str(auth_url))
request_token = gdata.gauth.AuthorizeRequestToken(request_token, self.request.uri
With the above code, I get to a grant access page and if you click the grant access page, you get a 404 error because it doesn't know where to go after (as expected), but the page has the proper URL displayed listing an oauth_verifier and oauth_token. The "AuthorizeRequestToken" line is supposed to use that URL to authorize the token so up to this line, everything seems to work.
When I add the following line right after the code above, I get the "RequestError" I wrote about:
access_token = docsClient.GetAccessToken(request_token)
I've tried different combinations of nesting the calls within each other, using the AeSave and AeLoad (as the instructions mention might be needed but I'm not sure if my case calls for it) and many other random and unsuccessful ideas and nothing is really giving me a good idea of what I'm missing or doing wrong.
Would really appreciate and help or any ideas anyone has.(If you can't tell, I'm fairly inexperienced when it comes to real-world code (as opposed to academic code). Thanks so much.

Programmatically get the list of versions from appengine

I'd like to get a list of deployed versions from appengine, either from the remote API or via appcfg.py. I can't seem to find any way to do it, certainly not a documented way. Does anyone know of any way to do this (even undocumented)?
You can list deployed versions in the admin console under "Admin Logs". Short of screen-scraping this page, there's no way to access this data programmatically.
You can submit this as an enhancement request to the issue tracker.
I was able to do this by copying some of the RPC code from appcfg.py into my application. I posted up this gist that goes into detail on how to do this, but I will repeat them here for posterity.
Install the python API client. This will give you the OAuth2 and httplib2 libraries you need to interact with Google's RPC servers from within your application.
Copy this file from the GAE SDK installed on your development machine: google/appengine/tools/appengine_rpc_httplib2.py into your GAE webapp.
Obtain a refresh token by executing appcfg.py list_versions . --oauth2 from your local machine. This will open a browser so you can login to your Google Account. Then, you can find the refresh_token in ~/.appcfg_oauth2_tokens
Modify and run the following code inside of a web handler:
Enjoy.
from third_party.google_api_python_client import appengine_rpc_httplib2
# Not-so-secret IDs cribbed from appcfg.py
# https://code.google.com/p/googleappengine/source/browse/trunk/python/google/appengine/tools/appcfg.py#144
APPCFG_CLIENT_ID = '550516889912.apps.googleusercontent.com'
APPCFG_CLIENT_NOTSOSECRET = 'ykPq-0UYfKNprLRjVx1hBBar'
APPCFG_SCOPES = ['https://www.googleapis.com/auth/appengine.admin']
source = (APPCFG_CLIENT_ID,
APPCFG_CLIENT_NOTSOSECRET,
APPCFG_SCOPES,
None)
rpc_server = appengine_rpc_httplib2.HttpRpcServerOauth2(
'appengine.google.com',
# NOTE: Here's there the refresh token is used
"your OAuth2 refresh token goes here",
"appcfg_py/1.8.3 Darwin/12.5.0 Python/2.7.2.final.0",
source,
host_override=None,
save_cookies=False,
auth_tries=1,
account_type='HOSTED_OR_GOOGLE',
secure=True,
ignore_certs=False)
# NOTE: You must insert the correct app_id here, too
response = rpc_server.Send('/api/versions/list', app_id="khan-academy")
# The response is in YAML format
parsed_response = yaml.safe_load(response)
if not parsed_response:
return None
else:
return parsed_response
Looks like Google has recently released a get_versions() function in the google.appengine.api.modules package. I recommend using that over the hack I implemented in my other answer.
Read more at:
https://developers.google.com/appengine/docs/python/modules/functions

Categories

Resources