Git Product home page Git Product logo

spotipy's Introduction

Spotipy

Spotipy is a lightweight Python library for the Spotify Web API. With Spotipy you get full access to all of the music data provided by the Spotify platform.

Tests Documentation Status

Table of Contents

Features

Spotipy supports all of the features of the Spotify Web API including access to all end points, and support for user authorization. For details on the capabilities you are encouraged to review the Spotify Web API documentation.

Installation

pip install spotipy

alternatively, for Windows users

py -m pip install spotipy

or upgrade

pip install spotipy --upgrade

Quick Start

A full set of examples can be found in the online documentation and in the Spotipy examples directory.

To get started, install spotipy, create a new account or log in on https://developers.spotify.com/. Go to the dashboard, create an app and add your new ID and SECRET (ID and SECRET can be found on an app setting) to your environment (step-by-step video):

Example without user authentication

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id="YOUR_APP_CLIENT_ID",
                                                           client_secret="YOUR_APP_CLIENT_SECRET"))

results = sp.search(q='weezer', limit=20)
for idx, track in enumerate(results['tracks']['items']):
    print(idx, track['name'])

Expected result:

0 Island In The Sun
1 Say It Ain't So
2 Buddy Holly
.
.
.
18 Troublemaker
19 Feels Like Summer

Example with user authentication

A redirect URI must be added to your application at My Dashboard to access user authenticated features.

import spotipy
from spotipy.oauth2 import SpotifyOAuth

sp = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id="YOUR_APP_CLIENT_ID",
                                               client_secret="YOUR_APP_CLIENT_SECRET",
                                               redirect_uri="YOUR_APP_REDIRECT_URI",
                                               scope="user-library-read"))

results = sp.current_user_saved_tracks()
for idx, item in enumerate(results['items']):
    track = item['track']
    print(idx, track['artists'][0]['name'], " – ", track['name'])

Expected result will be the list of music that you liked. For example if you liked Red and Sunflower, the result will be:

0 Post Malone  –  Sunflower - Spider-Man: Into the Spider-Verse
1 Taylor Swift  –  Red

Reporting Issues

For common questions please check our FAQ.

You can ask questions about Spotipy on Stack Overflow. Don’t forget to add the Spotipy tag, and any other relevant tags as well, before posting.

If you have suggestions, bugs or other issues specific to this library, file them here. Or just send a pull request.

Contributing

If you are a developer with Python experience, and you would like to contribute to Spotipy, please be sure to follow the guidelines listed on documentation page

spotipy's People

Contributors

alexey-v-paramonov avatar baschdl avatar beahmer89 avatar cyanbook avatar darwady2 avatar dieser-niko avatar eugenio412 avatar foobuzz avatar gustavokrieger avatar happyleavesaoc avatar harrison97 avatar hughrawlinson avatar hugovk avatar idmfoundinhim avatar johncheng2011 avatar jsundram avatar kevinmgranger avatar mattduck avatar matthewjohn avatar mbirtwell avatar nathancoleman avatar peter-schorn avatar plamere avatar ritiek avatar ryn3 avatar sr-murthy avatar stephanebruckert avatar tonyaajjackson avatar yashsinha848 avatar ysinjab avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

spotipy's Issues

user_playlists() not returning full list

Previously, user_playlists returned a complete list of the users playlists, including starred playlists, and collaborative playlists they created/followed.

Now, the request does not return starred playlists or collaborative playlists.

Search picks up "Welcome to Spotipy!"

I searched for something and search results says:

Search Results

Search finished, found 12 page(s) matching the search query.

spotipy.client.Spotify.track (Python method, in Welcome to Spotipy!)
spotipy.client.Spotify.album_tracks (Python method, in Welcome to Spotipy!)
spotipy.client.Spotify.artist_top_tracks (Python method, in Welcome to Spotipy!)
spotipy.client.Spotify.current_user_saved_tracks (Python method, in Welcome to Spotipy!)
spotipy.client.Spotify.current_user_saved_tracks_add (Python method, in Welcome to Spotipy!)
spotipy.client.Spotify.current_user_saved_tracks_delete (Python method, in Welcome to Spotipy!)
spotipy.client.Spotify.tracks (Python method, in Welcome to Spotipy!)
spotipy.client.Spotify.user_playlist_add_tracks (Python method, in Welcome to Spotipy!)
spotipy.client.Spotify.user_playlist_remove_all_occurrences_of_tracks (Python method, in Welcome to Spotipy!)
spotipy.client.Spotify.user_playlist_remove_specific_occurrences_of_tracks (Python method, in Welcome to Spotipy!)
spotipy.client.Spotify.user_playlist_replace_tracks (Python method, in Welcome to Spotipy!)
Welcome to Spotipy!
...print(album['name']) Here's another example showing how to get 30 second samples and cover art for the top 10 tracks for Led Zeppelin:: import spotipy lz_uri = 'spotify:artist:36QJpDe2go2KgaRleHCDTp' spotify = spoti...

"Python method, in Welcome to Spotipy" is perhaps not what you want it to display in search results.
It's picking up the name of the project from the title in index.rst "Welcome to Spotipy!" ?

Redirect URI Redirect doesn't work with http://localhost:8888/callback

I've been trying to get authentication up and running with this API, I have followed the steps in the documentation and attempted to use http://localhost:8888/callback as the redirect URI both in the spotify developer page and in my app.

Has anyone else been able to get this working in Python3 and if so what did you use for your redirects?

Can't log in to spotify

So maybe I'm missing something here, but when I run the example program and it gives me a link to visit, I get to a log in screen, but when I try to click log in, nothing happens. I can click the log in through facebook link and this logs me in but when I paste it as the redirected link in spotipy, it raises an exception:

    raise SpotifyOauthError(response.reason)
spotipy.oauth2.SpotifyOauthError: Bad Request

Am I doing something wrong? I have my credentials set as environment variables and I'm using http://example.com/callback/ as my redirect uri

how can i get track by artist?

how can i get some tracks?
i use sp.search() (example: sp.search('rap god','1','0','track') )
i want to get (rap god-eminem)
what use i query?

Login issue

I've been trying countless different methods, and getting the code and callback, but my application keeps saying "bad request". See below:

# set environment variables
os.environ["SPOTIPY_CLIENT_ID"] = c_id
os.environ["SPOTIPY_CLIENT_SECRET"] = c_secret
os.environ["SPOTIPY_REDIRECT_URI"] = callback_uri
token = util.prompt_for_user_token(username, scope)

and the output:

Opening https://accounts.spotify.com/...output_omitted...

Enter the URL you were redirected to: http://localhost:8888/...output_omitted...

Traceback (most recent call last):
File "./HotUnity.py", line 24, in
token = util.prompt_for_user_token(username, scope)
File "build/bdist.macosx-10.11-intel/egg/spotipy/util.py", line 86, in prompt_for_user_token
File "build/bdist.macosx-10.11-intel/egg/spotipy/oauth2.py", line 210, in get_access_token
spotipy.oauth2.SpotifyOauthError: Bad Request

Problem running sample code

I ran the sample code "Shows the contents of every playlist owned by a user:" from here:
http://spotipy.readthedocs.io/en/latest/#examples

and got this Terminal sequence:

$ python /Users/me/Documents/test/python/hello_spotipy.py myuseracount


            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?redirect_uri=<some url> in your browser

Enter the URL you were redirected to: 

I've white-listed my redirect_uri, exported id/secret/redirect_uri (double-checked that all changes are in effect), and ran the code as is. But the URL opened in my browser says:

Error
Oops! Something went wrong, please try again or check out our help area.

The same happened after I removed the "remembered" Spotify credential from my browsers (Safari, Chrome).

Spotify denying access for valid Id

I am trying to access Spotify playlists using the spotipy and pbl libraries. See http://pbl.readthedocs.io/en/latest/ for the latter.

I have this:

import sys
from pbl import *
import spotipy
import spotipy.util as util


def fetch(): #pbl methods here

    classic_rock = Sample(PlaylistSource('Rock Classics'), sample_size=10)
    new_music = Sample(PlaylistSource('New Music Tuesday'), sample_size=5)
    combined = Shuffler(Concatenate([classic_rock, new_music]))
    show_source(combined)

scope = 'playlist-modify-public'

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='a_valid_id', client_secret='a_valid_secret', redirect_uri='http://localhost:8888/callback')

if token:
    sp = spotipy.Spotify(auth=token)
    fetch()

If I bypass the snippet relative to pbl methods and the pbl function call above and proceed, I am granted access.

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

Otherwise access is denied, and I get spotipy.oauth2.SpotifyOauthError: No client id

what is going on here? please help.

Support refreshing token

What is the recommendation of this team for how people should refresh tokens? As it stands all examples are written as though you've just gotten your tokens from a prompt. If I go deep into oauth2.py I can find a private method to refresh tokens however, that requires a whole different object that the standard spotipy instance does not need.

This is a critical part of the library. How do you anticipate this flow working?

user_playlist_add_track error

Hey I'm just starting to get familiar with the api, and I'm just trying out a simple task. I'm trying to add the top 3 tracks of a given artist to a playlist.

I know authentication worked because I can access the playlists, and I set my scope to playlist-modify-private and public.

I use the following command:

sp.user_playlist_add_tracks(user, playlist_id, song['uri'])

This is the value of song['uri']:

song_uri
Out[20]: u'spotify:track:2Zb7wnGUnNPCas2E0wWSQ5'

Here's the error message:

http status: 400, code:-1 - the requested resource could not be found: https://api.spotify.com/v1/users/121142162/playlists/3LhmfLB345HX1tty3Z99u7/tracks?uris=s%2Cp%2Co%2Ct%2Ci%2Cf%2Cy%2C%3A%2Ct%2Cr%2Ca%2Cc%2Ck%2C%3A%2C2%2CZ%2Cb%2C7%2Cw%2Cn%2CG%2CU%2Cn%2CN%2CP%2CC%2Ca%2Cs%2C2%2CE%2C0%2Cw%2CW%2CS%2CQ%2C5

It seems like the uri's match up, ignoring how colons were decoded. Any ideas what the issue is?

current_user_saved_albums() not working

hello all,

when I execute
results = sp.current_user_saved_albums()

I get the error
AttributeError: 'Spotify' object has no attribute 'current_user_saved_albums'

Contrary sp.current_user_saved_tracks() works fine. Does anyone has an idea why?

Thanks for any help

Charts API

Spotify recently made an update to their Spotify Viral Charts, which used to be available here: http://charts.spotify.com/.

They are now available only via the web player itself: https://play.spotify.com/chart/6o9o1UphRtyv10VPuDT80D and I was wondering if there is a Spotipy solution to grab the songs from the Viral charts into Python.

As an example, here is the Global Viral 50 chart I would like to pull data on: spotify:app:chart:6o9o1UphRtyv10VPuDT80D

Any help would be greatly appreciated.

Use logging instead of print

Print statements, even in exception handling, makes it impossible for those using your client to actually control the output while building their own application. I'd be happy to provide a PR if it would be appreciated, but don't want to sync time into it if not.

Abstraction of caching code

I'm using spotipy on Heroku as a Slack bot - which works awesomely, but I've had to store the cached token on S3. I've extended SpotifyOAuth and overridden get_cached_token and _save_token_info to do this, but it'd be useful if it was possible to do this without extensio?. This would also allow for storing the token in a DB rather than in a file.

Maybe the simplest approach could be load_cached_token and save_cached_token methods, which can be overridden to cater for different storage approaches?

Incomplete output in example show_my_saved_tracks

This is a detail but maybe useful for beginners. In example show_my_saved_tracks, the output does not display all saved tracks but only some of them. To fix that, something similar to what's done in user_playlists_contents should be used, eg

results = sp.current_user_saved_tracks()
show_tracks(results)
while results['next']:
  results = sp.next(results)
  show_tracks(results)

with

def show_tracks(results):
    for i, item in enumerate(results['items']):
        track = item['track']
        print("   %d %32.32s %s" % (i, track['artists'][0]['name'], track['name']))

Redirect loop when running on Google App Engine with Task Queue

Hi Paul,

I'm not sure if this is a GAE problem, a requests problem, or something on Spotify's end, but I'm opening this here to make sure it's not the latter.

I have some python code that looks similar to the following:

import spotipy
Spotify = spotipy.Spotify()

def some_task_queue_handler(request):
    spotify_uri = get_spotify_uri_from_task_queue_request(request)
    metadata = Spotify.track(spotify_uri)
    logging.info("metadata is: %s", metadata)
    return None, 204

The issue that I'm running into is that both locally and when deployed, the spotipy requests are resulting in a redirect loop, where the location set by the redirect response is exactly the same every time. I've modified the requests session handler a little bit to print out the history that it collects when following redirects, and I get 30 items that look identical to this:

CaseInsensitiveDict({'content-length': '178', 'via': 'HTTP/1.1 GWA', 'x-google-cache-control': 'remote-fetch', 'server': 'nginx', 'connection': 'keep-alive', 'location': 'https://api.spotify.com/v1/tracks/2wNO69huzAY2WBnigjXMQ4', 'date': 'Thu, 09 Apr 2015 20:32:17 GMT', 'content-type': 'text/html'})

Is this bouncing happening on the Spotify end? Possibly due to some user agent or origin IP? Or Do I need to set an auth parameter to make the call from a GAE server?

When I run curl on the same URL from my local command line, I get a valid response:

rknLA:~() $ curl -v https://api.spotify.com/v1/tracks/2wNO69huzAY2WBnigjXMQ4                                                                                                                                                                          09.04.2015 [22:52:11]
* Hostname was NOT found in DNS cache
*   Trying 194.14.177.4...
* Connected to api.spotify.com (194.14.177.4) port 443 (#0)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
* Server certificate: *.spotify.com
* Server certificate: DigiCert SHA2 Secure Server CA
* Server certificate: DigiCert Global Root CA
> GET /v1/tracks/2wNO69huzAY2WBnigjXMQ4 HTTP/1.1
> User-Agent: curl/7.37.1
> Host: api.spotify.com
> Accept: */*
>
< HTTP/1.1 200 OK
* Server nginx is not blacklisted
< Server: nginx
< Date: Thu, 09 Apr 2015 20:52:19 GMT
< Content-Type: application/json; charset=utf-8
< Content-Length: 2488
< Connection: keep-alive
< Keep-Alive: timeout=600
< Vary: Accept-Encoding
< Cache-Control: public, max-age=7200
< Access-Control-Allow-Headers: Accept, Authorization, Origin, Content-Type
< Access-Control-Allow-Origin: *
< Access-Control-Max-Age: 604800
< Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE
< Access-Control-Allow-Credentials: true
< X-Content-Type-Options: nosniff
< Strict-Transport-Security: max-age=31536000;
<
{
  "album" : {
    "album_type" : "single",
    "available_markets" : [ "AD", "AR", "AT", "AU", "BE", "BG", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "EC", "EE", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "IE", "IS", "IT", "LI", "LT", "LU", "LV", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "PA", "PE", "PH", "PL", "PT", "PY", "RO", "SE", "SG", "SI", "SK", "SV", "TR", "TW", "US", "UY" ],
    "external_urls" : {
      "spotify" : "https://open.spotify.com/album/70g5xd035UlaLDn1bFPHHM"
    },
    "href" : "https://api.spotify.com/v1/albums/70g5xd035UlaLDn1bFPHHM",
    "id" : "70g5xd035UlaLDn1bFPHHM",
    "images" : [ {
      "height" : 640,
      "url" : "https://i.scdn.co/image/54ef204750e0c36c9facfac3fd8148a2ed6fead8",
      "width" : 640
    }, {
      "height" : 300,
      "url" : "https://i.scdn.co/image/d60bde19570f4880fde094185cdb750271ebcda4",
      "width" : 300
    }, {
      "height" : 64,
      "url" : "https://i.scdn.co/image/ad556ebf704e4450ce6152c5f4e66cab0636b2de",
      "width" : 64
    } ],
    "name" : "Project Destati: Awakening",
    "type" : "album",
    "uri" : "spotify:album:70g5xd035UlaLDn1bFPHHM"
  },
  "artists" : [ {
    "external_urls" : {
      "spotify" : "https://open.spotify.com/artist/7q3OTml6VefMn69k5EOwnx"
    },
    "href" : "https://api.spotify.com/v1/artists/7q3OTml6VefMn69k5EOwnx",
    "id" : "7q3OTml6VefMn69k5EOwnx",
    "name" : "Project Destati",
    "type" : "artist",
    "uri" : "spotify:artist:7q3OTml6VefMn69k5EOwnx"
  } ],
  "available_markets" : [ "AD", "AR", "AT", "AU", "BE", "BG", "BO", "BR", "CA", "CH", "CL", "CO", "CR", "CY", "CZ", "DE", "DK", "DO", "EC", "EE", "ES", "FI", "FR", "GB", "GR", "GT", "HK", "HN", "HU", "IE", "IS", "IT", "LI", "LT", "LU", "LV", "MC", "MT", "MX", "MY", "NI", "NL", "NO", "NZ", "PA", "PE", "PH", "PL", "PT", "PY", "RO", "SE", "SG", "SI", "SK", "SV", "TR", "TW", "US", "UY" ],
  "disc_number" : 1,
  "duration_ms" : 311749,
  "explicit" : false,
  "external_ids" : {
    "isrc" : "USE830908262"
  },
  "external_urls" : {
    "spotify" : "https://open.spotify.com/track/2wNO69huzAY2WBnigjXMQ4"
  },
  "href" : "https://api.spotify.com/v1/tracks/2wNO69huzAY2WBnigjXMQ4",
  "id" : "2wNO69huzAY2WBnigjXMQ4",
  "name" : "Sinister Sunburn",
  "popularity" : 28,
  "preview_url" : "https://p.scdn.co/mp3-preview/87603ffc63bc0ba98c37145e07287fdf3d7baffc",
  "track_number" : 3,
  "type" : "track",
  "uri" : "spotify:track:2wNO69huzAY2WBnigjXMQ4"
* Connection #0 to host api.spotify.com left intact
}%

Thanks!

Cannot authenticate due to bad authentication URL

When I try authenticate a user I get an unexplained error when visiting the authentication URL.

After investigating this I found that when urllib encodes a redirect URL it removes the 'http://' from the beginning e.g. 'http://davecarpie.github.io' becomes 'davecarpie.github.io' rather than 'http%3A%2F%2Fdavecarpie.github.io'.

I tried authenticating manually using the url with the http:// in it and was successful. When registering a new application Spotify also forces you to have the protocol in the URI so I'm fairly sure that is the reason authentication is unsuccessful.

Using the requests library encodes the URI properly so using that instead of urllib could work? I'm happy to make the change and submit a pull request if you want?

analysis_url

Hi!

I'm suddenly no longer able to access analysis_url and very curious to find out if I'm the only one experiencing this problem. I'm getting error status 401 with the message "No token provided". I'm using the prompt_for_user_token function to authenticate.

Thank you in advance!
-Snippern

Installation issue

When i import spotipy, i am told there is no module named client? What am i doing wrong?

Weird/intermittent Behaviour: JSONDecodeError: Expecting value: line 1 column 1 (char 0)

I had this working for 2+ months but today it was erroring intermittently????
Would appreciate your help!

> > > type(user)
> > > <class 'spotipy.client.Spotify'>
> > > user_saved_tracks= user.current_user_saved_tracks(limit=50)
> > > user_saved_tracks= user.current_user_saved_tracks(limit=50)
> > > user_saved_tracks= user.current_user_saved_tracks(limit=50)
> > > user_saved_tracks= user.current_user_saved_tracks(limit=50)
> > > user_saved_tracks= user.current_user_saved_tracks(limit=50)
> > > user_saved_tracks= user.current_user_saved_tracks(limit=50)
> > > Traceback (most recent call last):
> > >   File "<console>", line 1, in <module>
> > >   File "/usr/local/lib/python2.7/dist-packages/spotipy/client.py", line 466, in current_user_saved_tracks
> > >     return self._get('me/tracks', limit=limit, offset=offset)
> > >   File "/usr/local/lib/python2.7/dist-packages/spotipy/client.py", line 120, in _get
> > >     return self._internal_call('GET', url, payload, kwargs)
> > >   File "/usr/local/lib/python2.7/dist-packages/spotipy/client.py", line 104, in _internal_call
> > >     -1, u'%s:\n %s' % (r.url, r.json()['error']['message']))
> > >   File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 799, in json
> > >     return json.loads(self.text, **kwargs)
> > >   File "/usr/local/lib/python2.7/dist-packages/simplejson/__init__.py", line 505, in loads
> > >     return _default_decoder.decode(s)
> > >   File "/usr/local/lib/python2.7/dist-packages/simplejson/decoder.py", line 370, in decode
> > >     obj, end = self.raw_decode(s)
> > >   File "/usr/local/lib/python2.7/dist-packages/simplejson/decoder.py", line 400, in raw_decode
> > >     return self.scan_once(s, idx=_w(s, idx).end())
> > > JSONDecodeError: Expecting value: line 1 column 1 (char 0)

make file issue

I think there's an issue when using the makefile, in the docs folder. I'm doing the command
make man
For some reason, I keep getting this error:

sphinx-build -b man -d _build/doctrees   . _build/man
make: sphinx-build: No such file or directory
make: *** [man] Error 1

Authorisation with Heroku

Hi there,

I have built an app locally using spotipy (thanks for your awesome code!) and I'm trying to push it online with Heroku. I use the util.prompt_for_user_token() function to authorise the user_playlist_create function. Since the util function requires a command line raw input I can't understand how it will work when I push it online - can you a suggest a way that I can by pass this problem?

Many thanks!

Issy

Login Issue

Hello,

Just up front this may all be my ignorance of this api, but I'm currently not able to be login.

I'm calling

import sys
import spotipy
import spotipy.util as util

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='my_id_here', 
                        client_secret='my_secret_here',
                        redirect_uri='https:\\www.google.com')

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

and the issue I am running into is that when I login my web browser opens and goes to Spotify's error page and when I enter that url I (obviously) run into this:

line 16, in <module>
    redirect_uri='https:\\www.google.com')
  File "/Users/duncanwilson/anaconda2/lib/python2.7/site-packages/spotipy/util.py", line 86, in prompt_for_user_token
    token_info = sp_oauth.get_access_token(code)
  File "/Users/duncanwilson/anaconda2/lib/python2.7/site-packages/spotipy/oauth2.py", line 210, in get_access_token
    raise SpotifyOauthError(response.reason)
spotipy.oauth2.SpotifyOauthError: Bad Request

I've learned that this error is caused by the user already being logged in; but as soon as I logout then the redirect breaks when I attempt to login....

Thanks in advance! :)

Spotipy Object is not threadsafe with respect to request sessions and connection pools

When a single Spotipy object is used in multiple threads talking to the same endpoint, depending on timing, connection pool closed errors can occur. This happens because after every request made in _internal_call "close" is called on the request connection which in turn closes the session's pool for that end point. If another thread has already come in and been given a reference to that pool then tries to use it later, it will get this pool closed exception

"401 error: The access token expired" when using SpotifyClientCredentials

I am creating my Spotipy object like this, after reading this code snippet:

scc = SpotifyClientCredentials(client_id = SPOTIPY_CLIENT_ID,
                                   client_secret = SPOTIPY_CLIENT_SECRET)
sp = spotipy.Spotify(client_credentials_manager = scc)

However, after a number of queries, I obtain the following error:

http status:401                                                                 
Traceback (most recent call last):                                              
  File "retriever2.py", line 114, in <module>                                   
    store_songs(terms, dbfile, total_number)                                    
  File "retriever2.py", line 97, in store_songs                                 
    songs = get_songs(sp, playlist)                                             
  File "retriever2.py", line 36, in get_songs                                   
    track_results = sp.next(track_results)                                      
  File "/home/chema/.local/lib/python2.7/site-packages/spotipy/client.py", line 172, in next
    return self._get(result['next'])                                            
  File "/home/chema/.local/lib/python2.7/site-packages/spotipy/client.py", line 123, in _get
    return self._internal_call('GET', url, payload, kwargs)                     
  File "/home/chema/.local/lib/python2.7/site-packages/spotipy/client.py", line 104, in _internal_call
    -1, '%s:\n %s' % (r.url, r.json()['error']['message']))                     
spotipy.client.SpotifyException: http status: 401, code:-1 - https://api.spotify.com/v1/users/1248788010/playlists/4wEVX1M28mBIpiHttM6PrP/tracks?offset=100&limit=100:
 The access token expired      

I was under the impression that SpotifyClientCredentials was used to update the access token accordingly. Right now, I have my queries inside a try - except block and I refresh it manually (I basically recreate the sp object every time I get an exception). Am I using this correctly or is there any other way?

Album release date

Currently, "artist_albums()" doesn't return the album's release date. The release_date can only be found when calling "album()" or "albums()".

Can we bring this "release_date" field into the artist_albums return data?

Removing local files from playlists

So I have been trying to find a way to remove a local file from a playlist but I can't get it to work any way. I can't really find a function which would do what I need. Both remove_tracks functions require one or another type of argument which has to have track URI. But at least by looking at the Web API on Spotify page it says that it can only be done by using snapshot-id and position (https://developer.spotify.com/web-api/local-files-spotify-playlists/),

'It is not currently possible to add local files to playlists using the Web API, but they can be reordered or removed. The latter should be done by specifying the index and snapshot_id, and NOT the URI of the track.'

So can such functionality be implemented in a new release?

Can't search with > 1 query field

In [11]: sp.search('track:Unbelievers+artist:Vampire Weekend', type='track', limit=1)
Out[11]:
{u'tracks': {u'href': u'https://api.spotify.com/v1/search?query=track%3AUnbelievers%2Bartist%3AVampire+Weekend&offset=0&limit=1&type=track',
  u'items': [],
  u'limit': 1,
  u'next': None,
  u'offset': 0,
  u'previous': None,
  u'total': 0}}

Pointing a browser to the above link in the 'href' field and replacing the %2B with a + returns a populated track object, so I don't think the conversion from + to %2B that's happening somewhere along the Spotipy.search call stack should be happening...can it be avoided?

I also noticed there were no search calls in the examples that specified > 1 field.

[PYTHON3]Can't even import spotipy

I've installed spotipy using pip, no errors.
When I run python 3 and do import spotipy here's what I get:

File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.4/dist-packages/spotipy/__init__.py", line 2, in <module> from client import Spotify, SpotifyException ImportError: No module named 'client'

OS: Ubuntu 14.04,
Python: 3.4.0

number of playlist subscribers

Hi

Thank you for Spotipy! It's awesome. One quick question:

Is it possible to get the number of subscribers to a playlist using Spotipy?ck

I tried asking this on stackoverflow using the Spotipy tag which doesn't seem to exist

Thank you

Tom

Can't access "album object (full)" of a artist

Hello,

I wanted to write a new release notification script and therefor I need to access the "album object (full)" (https://developer.spotify.com/web-api/object-model/#album-object-full) of an artist.

When I load a artists albums via

albumResult = spotify.artist_albums(artistId, album_type="album", country=spotifyMarket, offset=offset)
albums = albumResult["items"]

I only have access to the simplified data. Not the release date of an album. Can somebody help me?

@plamere spotipy is class! Very helpful. Thank you big time.

michael

user_playlists_contents.py and user_starred_playlist.py examples failing

I tried StackOverflow first, as I thought this was more something I was doing wrong and less a problem with the code itself, but I was redirected here. Anyways, here's what I wrote at Stack Overflow:

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.

get_cached_token() should check scopes too

Started playing with this library to learn Python, and I kept getting an "insufficient scope" error from Spotify.

It turns out that if your application gets issued a token, and the application's required scope changes to need more permissions before that token expires, get_cached_token() in oauth2.py will still give that token back even though Spotify will reject it. When tokens are cached, information about what scopes are associated with that token needs to be recorded too.

encode error

Traceback (most recent call last):
File "playlist.py", line 30, in
print playlist['name']
File "C:\Python27\lib\encodings\cp850.py", line 12, in encode
return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode character u'\u2013' in position
11: character maps to

so u'\u2013' is a dash "-"

Examples Require Missing Library

The playlist-related examples attempt to import a util module. For example, line 10 of user_playlists.py reads:

import util

It is unclear where this module comes from. It is unavailable on my system (Python 2.7.3), and Google is of no help.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.