Hi everyone I'm seeing tutorials of Spotify API but I have one doubt, it's possible to send directly from code comands like play, next or play an specific song?
And if you are playing spotify in your phone it will change the song?
Update 1: This is the code that I have at the moment but I have this error message when I run it: (HELP WITH THIS)
SpotifyException: http status: 403, code:-1 - https://api.spotify.com/v1/me/player/play:
Player command failed: Premium required, reason: PREMIUM_REQUIRED
And this is my code:
from spotipy.oauth2 import SpotifyClientCredentials
import spotipy
client_id = ""
client_secret = ""
autor = 'Radiohead'
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials(client_id, client_secret))
result = sp.search(autor)
print(result)
#
sp.start_playback(uris=['spotify:artist:4Z8W4fKeB5YxbusRsdQVPb'])
Here is working code:
import spotipy
from spotipy.oauth2 import SpotifyOAuth
from pprint import pprint
client_id = ""
client_secret = ""
redirect_uri = ""
scope = "user-read-playback-state,user-modify-playback-state"
sp = spotipy.Spotify(
auth_manager=spotipy.SpotifyOAuth(
client_id=client_id,
client_secret=client_secret,
redirect_uri=redirect_uri,
scope=scope, open_browser=False))
# Shows playing devices
res = sp.devices()
pprint(res)
# Change track
sp.start_playback(uris=['spotify:track:6gdLoMygLsgktydTQ71b15'])
You have to put a dummy redirect URL inside the code and in the dashboard of your app.
The script will ask “Go to the following URL:”, and after logging in, you'll need copy the resulting URL after “Enter the URL you was redirected to:”.
Related
I want to experiment with the Spotify API using the Spotipy python package.
So to start, in my Spotify Developer app,
I have set the redirect_uri to https://example.com/callback/
This is the code I am trying to run on a Google Colab notebook
import pandas as pd
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
spotify_details = {
'client_id' : '<hidden>',
'client_secret':'<hidden>',
'redirect_uri':'https://example.com/callback/'}
scope = "user-library-read user-follow-read user-top-read playlist-read-private"
sp = spotipy.Spotify(
auth_manager=spotipy.SpotifyOAuth(
client_id=spotify_details['client_id'],
client_secret=spotify_details['client_secret'],
redirect_uri=spotify_details['redirect_uri'],
scope=scope))
results = sp.current_user_saved_tracks()
for idx, item in enumerate(results['items']):
track = item['track']
print(idx, track['artists'][0]['name'], " – ", track['name'])
This is what I see as the output:
But my browser does not redirect me to any URL for me to receive an auth token
What am I doing wrong?
Colab is a browserless environment, so as suggested in the FAQ you should add the parameter
open_browser=False
when you instantiate your spotipy.SpotifyOAuth object:
sp = spotipy.Spotify(
auth_manager=spotipy.SpotifyOAuth(
client_id=spotify_details['client_id'],
client_secret=spotify_details['client_secret'],
redirect_uri=spotify_details['redirect_uri'],
scope=scope, open_browser=False))
In this way, the notebook will print out the URL that you can open manually:
I'm attempting to call the Spotify API and have set up an app/got my client ID and Secret. Here's an example of my code (with specifics blocked out):
import spotipy
import spotipy.util as util
from spotipy.oauth2 import SpotifyClientCredentials
cid ="xx"
secret = "xx"
username = "xx"
client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret)
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
scope = 'user-library-read playlist-read-private'
token = util.prompt_for_user_token(username,scope,client_id='http://localhost:8888/callback/',client_secret='http://localhost:8888/callback/',redirect_uri='http://localhost:8888/callback/')
if token:
sp = spotipy.Spotify(auth=token)
else:
print("Can't get token for", username)
cache_token = token.get_access_token()
sp = spotipy.Spotify(cache_token)
currentfaves = sp.current_user_top_tracks(limit=20, offset=0, time_range='medium_term')
print(currentfaves)
I've made sure my URL is exactly the same as what's registered in my Spotify app development page, and I've added the client ID, redirect URIs and client Secret keys to my environment variables.
So far a separate tab opens up (https://accounts.spotify.com/authorize?client_id=http%3A%2F%2Flocalhost%3A8888%2Fcallback%2F&response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A8888%2Fcallback%2F&scope=playlist-read-private+user-library-read) but I'm only getting 'INVALID_CLIENT: Invalid client' on that page. What can I do/change to make this work?
token = util.prompt_for_user_token(username,scope,client_id='http://localhost:8888/callback/',client_secret='http://localhost:8888/callback/',redirect_uri='http://localhost:8888/callback/')
Is there a typo in here, since you copied the redirect uri also as the client id and secret?
In order to access my playlists, I am using the following example code, which I got from spotipy documentation page:
import pprint
import sys
import os
import subprocess
import spotipy
import spotipy.util as util
client_id = 'my_id'
client_secret = 'my_secret'
redirect_uri = 'http://localhost:8000/callback/'
scope = 'user-library-read'
if len(sys.argv) > 1:
username = sys.argv[1]
else:
print "Usage: %s username" % (sys.argv[0],)
sys.exit()
token = util.prompt_for_user_token(username, scope, client_id, client_secret, redirect_uri)
if token:
sp = spotipy.Spotify(auth=token)
results = sp.current_user_saved_tracks()
for item in results['items']:
track = item['track']
print track['name'] + ' - ' + track['artists'][0]['name']
else:
print "Can't get token for", username
when I run the script with python myscript.py myusername, I get this:
User authentication requires interaction with your
web browser. Once you enter your credentials and
give authorization, you will be redirected to
a url. Paste that url you were directed to to
complete the authorization.
Opening https://accounts.spotify.com/authorize?scope=user-library-read&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback&response_type=code&client_id=d3b2f7a12362468daa393cf457185973 in your browser
Enter the URL you were redirected to:
then, if I enter http://localhost:8000/callback/, I get the following error:
token = util.prompt_for_user_token(username, scope, client_id, client_secret, redirect_uri)
File "/Library/Python/2.7/site-packages/spotipy/util.py", line 86, in prompt_for_user_token
token_info = sp_oauth.get_access_token(code)
File "/Library/Python/2.7/site-packages/spotipy/oauth2.py", line 210, in get_access_token
raise SpotifyOauthError(response.reason)
spotipy.oauth2.SpotifyOauthError: Bad Request
how do I fix this?
I ran the same example code and ran into the same issues. But got it working by running a server on localhost first python -m SimpleHTTPServer and then made my app's website http://localhost:8000 and my redirect http://localhost:8000 too. After that I opened a new terminal window and ran python myscript.py my_user_name the url then opened in my browser if it didn't open for you, you could just copy and paste the url link it gave you from this line in your terminal
Opening https://accounts.spotify.com/authorize?scope=user-library-read&redirect_uri=http%3A%2F%2Flocalhost%3A8000%2Fcallback&response_type=code&client_id=d3b2f7a12362468daa393cf457185973 in your browser
directly into your browser and you'll be greeted with a page that requests you give the app access to your account. After doing this the new url that you should copy and paste in the terminal will appear directly in the browser. You wont see anything happen afterwards because you need to print the token :
token = util.prompt_for_user_token(
username, scope, client_id, client_secret, redirect_uri)
if token:
print "token: ", token
sp = spotipy.Spotify(auth=token)
# code
else:
print "Can't get token for", username
I am using the Spotipy python library to interact with the Spotify web api. I have worked through the API and docs but I do not see a clear example that shows how the library supports the Authorization code flow ( https://developer.spotify.com/web-api/authorization-guide/#authorization-code-flow ).
I implemented a simple Authorization Code flow with the help of Spotipy. Maybe this is helpful for other people as well. Also on github: https://github.com/perelin/spotipy_oauth_demo
Here is the code:
from bottle import route, run, request
import spotipy
from spotipy import oauth2
PORT_NUMBER = 8080
SPOTIPY_CLIENT_ID = 'your_client_id'
SPOTIPY_CLIENT_SECRET = 'your_client_secret'
SPOTIPY_REDIRECT_URI = 'http://localhost:8080'
SCOPE = 'user-library-read'
CACHE = '.spotipyoauthcache'
sp_oauth = oauth2.SpotifyOAuth( SPOTIPY_CLIENT_ID, SPOTIPY_CLIENT_SECRET,SPOTIPY_REDIRECT_URI,scope=SCOPE,cache_path=CACHE )
#route('/')
def index():
access_token = ""
token_info = sp_oauth.get_cached_token()
if token_info:
print "Found cached token!"
access_token = token_info['access_token']
else:
url = request.url
code = sp_oauth.parse_response_code(url)
if code:
print "Found Spotify auth code in Request URL! Trying to get valid access token..."
token_info = sp_oauth.get_access_token(code)
access_token = token_info['access_token']
if access_token:
print "Access token available! Trying to get user information..."
sp = spotipy.Spotify(access_token)
results = sp.current_user()
return results
else:
return htmlForLoginButton()
def htmlForLoginButton():
auth_url = getSPOauthURI()
htmlLoginButton = "<a href='" + auth_url + "'>Login to Spotify</a>"
return htmlLoginButton
def getSPOauthURI():
auth_url = sp_oauth.get_authorize_url()
return auth_url
run(host='', port=8080)
If someone needs the working code here is my current.
Just remember to change the client_id, etc. I put them in config.py.
import spotipy
import spotipy.util as util
from config import CLIENT_ID, CLIENT_SECRET, PLAY_LIST, USER
import random
token = util.oauth2.SpotifyClientCredentials(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
cache_token = token.get_access_token()
spotify = spotipy.Spotify(cache_token)
results1 = spotify.user_playlist_tracks(USER, PLAY_LIST, limit=100, offset=0)
When I was trying to do this none of these answers really got me there unfortunately. When I ended up figuring it out I detailed how in this post: https://stackoverflow.com/a/42443878/2963703
I was using Django as my backend but all the spotify api oauth stuff is done in javascript so it should still be very useful for you.
The Spotipy library supports the Authorization Code flow, as documented here. For more information, you could also check out Spotipy's oAuth2 module and Util module.
I've really been struggling with getting OAuth to work with the WiThings API lately, using Python 3.3. For reference, here is the documentation for WiThings: http://www.withings.com/api
Now... As I've said, I have been working with the WiThings API in Python, using the requests library (http://docs.python-requests.org/en/latest/). Supposedly, this has built in support for OAuth 1.0.
Using this, when I put in my consumer key and consumer secret, then perform the token request, I get this response...
b'<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">\n<html><head>\n<title>413 Request Entity Too Large</title>\n</head><body>\n<h1>Request Entity Too Large</h1>\nThe requested resource<br />/index.php<br />\ndoes not allow request data with POST requests, or the amount of data provided in\nthe request exceeds the capacity limit.\n<hr>\n<address>Apache Server at oauth.withings.com Port 80</address>\n</body></html>\n'
Any idea what could be causing this? I have a feeling its WiThings specific... but their support is horrible.
Next, I did some more research, and found this: https://github.com/maximebf/python-withings
While also rather poorly documented, I installed it, and have this code:
from __future__ import unicode_literals
from urllib.parse import parse_qs
import requests
from requests_oauthlib import OAuth1
import withings
CONSUMER_KEY = "omitted"
CONSUMER_SECRET = "omitted"
auth = WithingsAuth(CONSUMER_KEY, CONSUMER_SECRET)
authorize_url = auth.get_authorize_url()
print("Go to %s allow the app and copy your oauth_verifier" %authorize_url)
oauth_verifier = raw_input('Please enter your oauth_verifier: ')
creds = auth.get_credentials(oauth_verifier)
client = WithingsApi(creds)
measures = client.get_measures(limit=1)
print("Your last measured weight: %skg" % measures[0].weight)
And get the following error...
File "withings.py", line 5, in <module>
import withjings
File C:\User_Directory\withings.py", line 11, in <module>
auth = WithingsAuth(CONSUMER_KEY, CONSUMER_SECRET)
NameError: name 'WithingsAuth' is not defined
Any help on either of these issues? Has anyone had success working with Withings in python?
Thanks for the help guys
It should be
from withings import WithingsAuth, WithingsApi
For me it works well I was able to extract my last measured weight.
You either need to import WithingsAuth from withings, or specify that you want to use the withings.WithingsAuth. Changing your code it becomes:
from __future__ import unicode_literals
try:
from urllib.parse import parse_qs
except:
import urlparse as parse_qs
try:
input_method = raw_input
except:
input_method = input
import requests
from requests_oauthlib import OAuth1
import withings
CONSUMER_KEY = "omitted"
CONSUMER_SECRET = "omitted"
auth = withings.WithingsAuth(CONSUMER_KEY, CONSUMER_SECRET)
authorize_url = auth.get_authorize_url()
print("Go to %s allow the app and copy your oauth_verifier" %authorize_url)
oauth_verifier = input_method('Please enter your oauth_verifier: ')
creds = auth.get_credentials(oauth_verifier)
client = withings.WithingsApi(creds)
measures = client.get_measures(limit=1)
print("Your last measured weight: %skg" % measures[0].weight)