I am trying to add tracks to one of my Spotify playlists, and I'm pretty sure I have all of the code exactly right as described in the Spotipy documentation:
username = '*myusername*'
scope = 'playlist-modify-public'
playlist_id = '*myplaylistid*'
track_ids = *array of track ids*
token = util.prompt_for_user_token(username,
scope,
client_id='*myclientid*',
client_secret='*mysecretclientid*',
redirect_uri='http://localhost:8888/callback/')
spotify = spotipy.Spotify(auth=token)
results = spotify.user_playlist_add_tracks(username, playlist_id, track_ids)
However, these are the following errors two errors that I receive no matter what I try:
HTTPError: 400 Client Error: Bad Request for url: https://api.spotify.com/v1/users/*myusername*/playlists/*myplaylist*/tracks
During handling of the above exception, another exception occurred:
SpotifyException: http status: 400, code:-1 - https://api.spotify.com/v1/users/*myusername*/playlists/*myplaylist*/tracks:
Invalid track uri: spotify:track:*trackid*
It specifies Invalid track uri, however for each of the tracks in my list I have tested by searching the uri in Spotify and it is indeed valid.
Solutions I have tried to no avail:
1. Changing between ID and URIs for both playlists and track list
2. Authenticating using OAuth
3. Using different playlists and tracks
4. Using different redirect_uri
5 example track URIs for reference:
spotify:track:1rdHsnsGmleo6MRctkkFmm?si=7R0IKQ9xTgiwfLAJO7eFCw
spotify:track:70CMnzQ3FjMmUk5NPdQJBe?si=qL_WwgWVRTaSZ2oOBg2eCA
spotify:track:6bbx7nYlixYuElKMbYCzMm?si=Wu64S-obRaOOh3mFP3zWwA
spotify:track:6DZNQKNUskiWVSXs3cQPk3?si=SIW3hBU1SiWd_h1gpXwijg
spotify:track:2FMPIU8FdP9kCi5kUCSGnE?si=jtJOkQhsSF6GoD3otgtV3A
Would appreciate any help!! Thank you
The track URIs should not contain ?si= but only what's before that. See https://developer.spotify.com/documentation/web-api/#spotify-uris-and-ids
You can fix your code to only keep the first part:
track_uris = [uri.split("?si=")[0] for uri in track_uris]
Related
Been working on a spotify / spotipy application which will add the current song to a certain playlist.
My functions for getting the current song and showing a playlist are all doing fine. My function for adding a song to a playlist is not.
I am getting the following error in my IDE:
http status: 405, code:-1 - https://api.spotify.com/v1/users/myUserID/playlists/myPlayListID/tracks:
error
When i copy paste the link to the browser i am getting the following error:
{
"error": {
"status": 401,
"message": "No token provided"
}
}
As far as i'm aware i'm providing a token.
Here is my function which makes the spotify object
def __createSpotifyObject(self):
"""Will create a spotify object and return it"""
# Defining the scope(s) of the application
scope = "playlist-modify-public playlist-modify-private user-read-currently-playing"
# Getting the token
token = util.prompt_for_user_token(username=USER_NAME, scope=scope, client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri="https://localhost/")
# Returning our spotify object
return spotipy.Spotify(auth=token)
Here is the function which tries to add a song to my playlist (this is where the error occurs)
I've tried catching the exception (which it did) and then trying to make a new spotify object so it will refresh the token or something like that. It just gives me the same error.
def addCurrentSongToSelectedPlaylist(self):
"""Will add the currently playing song to the selected playlist"""
# Checking if a playlist has been selected
if (len(self.__selectedPlaylist ) < 1):
print("No playlist selected")
return
# Getting the current song
currentSong = self.getCurrentSong()
# Adding the current song id to the selected playlist
try:
self.__spotify.user_playlist_add_tracks(USER, self.__selectedPlaylist, [currentSong["id"]])
except spotipy.client.SpotifyException:
# Re authenticating
self.__spotify = self.__createSpotifyObject()
self.__spotify.user_playlist_add_tracks(USER, self.__selectedPlaylist, [currentSong["id"]])
At this point the only thing I can think of is that the show playlist / show current playing song actions require less permission and that is why they work and the add song to playlist won't.
Found out i implemented the user wrong. instead of username?si=someNumbers i needed to just enter the username.
Edit:
Copy and pasting the adress of the error msg in to the browser is useless since it is a api call and it will always give back 401: no token provided due to trying to access it without a token.
Just stumbled across this beautifull list of what every error code means. https://developer.spotify.com/documentation/web-api/ This doesn't just apply to the web api but also to the Spotipy library. Check the error code in your IDE or editor against the list on this page.
I see there has been questions similar to this but the responses to them explains my asking a similar question here. I am wanting to utilize LinkedIn's REST API for my personal job hunt, specifically utilizing the job search API capabilities.
My problem comes in with retrieving an access token and autorisation to actually use the app. I have tried the below code - the first cell is to retrieve autorisation and the second is to retrieve an access token:
from linkedin import linkedin
APPLICATON_KEY = 'XXXXXX'
APPLICATON_SECRET = 'XXXXX'
RETURN_URL = 'http://localhost:8000'
authentication = linkedin.LinkedInAuthentication(APPLICATON_KEY, APPLICATON_SECRET, RETURN_URL,
linkedin.PERMISSIONS.enums.values())
print (authentication.authorization_url) #open this url on your browser
Access token:
authentication = linkedin.LinkedInAuthentication(
APPLICATON_KEY,
APPLICATON_SECRET,
RETURN_URL,
linkedin.PERMISSIONS.enums.values()
)
authentication.authorization_code = '#############################################'
result = authentication.get_access_token()
print ("Access Token:", result.access_token)
print ("Expires in (seconds):", result.expires_in)
When I attempt to retreieve authorisation (required for access token) the following error occurs:
File "/usr/local/lib/python3.6/dist-packages/linkedin/linkedin.py", line 294
except (requests.ConnectionError, requests.HTTPError), error:
^
SyntaxError: invalid syntax
It's an obvious syntax error, however am ignorant to what it is exactly - I have a feeling it might be my localhost
That error points to the comma separating the exception classes from the variable name.
A comma there is Python 2.x syntax, so that means the linkedin library you're using is not compatible with Python 3.
If you're using this library, you can see it's not been updated in 5 years. This (PyPI) seems like a slightly fresher fork.
I have tried multiple approaches to this. Tried first getting the user without any user id - this returns me just my user, then tried getting user with other id's and it also retrieves data correctly. However, I can't seem to be able to set user attribute 'deleted'. i'm using this python approach.
slack_client.api_call('users.profile.set', deleted=True, user='U36D86MNK')
However I get the error message of:
{u'error': u'invalid_user', u'ok': False}
Maybe someone has already done this? It says in documentation that it's a paid service mentioning this message under a user property:
This argument may only be specified by team admins on paid teams.
But shouldn't it give me a 'paid service' response in that case then?
The users.profile.set apparently does not work for for setting each and every property of a user.
To set the deleted property there is another API method called users.admin.setInactive. Its an undocumented method and it will only work on paid teams.
Note: This requires a legacy token and doesn't work with App tokens - these are only available on paid plans and new legacy tokens can't be created anymore
in python you can do the following:
import requests
def del_slack_user(user_id): # the user_id can be found under get_slack_users()
key = 'TOKEN KEY' #replace token key with your actual token key
payload = {'token': key, 'user': user_id}
response = requests.delete('https://slack.com/api/users.admin.setInactive', params=payload)
print(response.content)
def get_slack_users():
url = 'https://slack.com/api/users.list?token=ACCESSTOKEN&pretty=1'
response = requests.get(url=url)
response_data = response.json() # turns the query into a json object to search through`
You can use Slack's SCIM API to enable and disable a user. Note that, as with the undocumented API endpoint mentioned in other answers this requires a Plus/Enterprise account.
This is my code
UserScope = 'user-library-read'
util.prompt_for_user_token(username='vulrev1',scope=UserScope,client_id="533adb3f925b488za9d3772640ec6403",client_secret='66054b185c7541fcabce67afe522449b',redirect_uri="http://127.0.0.1/callback")
lz_uri = 'spotify:artist:36QJpDe2go2KgaRleHCDTp'
spotify = spotipy.Spotify()
results = spotify.artist_top_tracks(lz_uri)
for track in results['tracks'][:10]:
print ('track : ' + track['name'])
I'm getting this
spotipy.oauth2.SpotifyOauthError: Bad Request
I'm not quite sure what's going on here, is there something I need to do with the host files ? because http://127.0.0.1 refuses to connect
token = util.prompt_for_user_token(username='vulrev1',scope=UserScope,client_id="533adb3f925b488za9d3772640ec6403",client_secret='66054b185c7541fcabce67afe522449b',redirect_uri="http://127.0.0.1/callback")
spotify = spotipy.Spotify(auth=token)
You have to send your token as a auth. And also i think you must change your user ID to the specific numbers where u can find at the link of your profile.
I am trying to create a set on Quizlet.com, using its API found here: https://quizlet.com/api/2.0/docs/sets#add
Here is my code of a set I am trying to create:
import requests
quizkey = my_client_id
authcode = my_secret_code # I'm not sure if I need this or not
data = {"client_id":quizkey, "whitespace":1, "title":"my-api-set",
"lang_terms":"it", "lang_definitions":"en",
"terms":['uno','due'], "definitions":["one","two"]}
apiPrefix = "https://api.quizlet.com/2.0/sets"
r = requests.post(url=apiPrefix, params=data)
print r.text
The response is:
{
"http_code": 401,
"error": "invalid_scope",
"error_title": "Not Allowed",
"error_description": "You do not have sufficient permissions to perform the requested action."
}
I also tried "access_token":authcode instead of "client_id":quizkey, but this resulted in the error: "You do not have sufficient permissions to perform the requested action."
How can I fix this and not get a 401 error?
Alright so 3 and a half years later (!!) I've looked into this again and here's what I've discovered.
To add a set you need an access token - this is different to the client_id (what I call quizkey in my code), and to be quite honest I don't remember what authcode in my code is.
This token is obtained by going through the user authentication flow. To summarise it:
Send a POST request to https://quizlet.com/authorize like so:
https://quizlet.com/authorize?response_type=code&client_id=MY_CLIENT_ID&scope=read&state=RANDOM_STRING
Keep the response_type as code, replace client_id with your client_id, keep the scope as read, and state can be anything
I believe this requires human intervention because you're literally authorising your own account? Not sure of another way...
You'll receive a response back with a code
Let's call this RESPONSE_CODE for now
Send a POST request to https://api.quizlet.com/oauth/token, specifying 4 mandatory parameters:
grant_type="authorization_code" (this never changes)
code=RESPONSE_CODE
redirect_uri=https://yourredirecturi.com (this can be found at your personal API dashboard)
client ID and secret token separated by a colon and then base64-encoded (the user authentication flow link above tells you what this is if you don't want to do any of the encoding)
You'll receive the access_token from this API call
Now you can use that access_token in your call to create a set like I've done above (just replace "client_id":quizkey with "access_token":access_token)
You will need to authenticate in order to make sets. This link gives an overview:
https://quizlet.com/api/2.0/docs/making_api_calls
And this one provides details about the authentication process:
https://quizlet.com/api/2.0/docs/authorization_code_flow