Skip to main content

spotify.py is an asynchronous API wrapper for Spotify written in Python.

Project description

logo

Version infoGithub IssuesGithub forksGitHub starsLicenseDiscordTravis


spotify.py

An API library for the spotify client and the Spotify Web API written in Python.

Spotify.py is an asyncronous API library for Spotify. While maintaining an emphasis on being purely asyncronous the library provides syncronous functionality with the spotify.sync module.

import spotify.sync as spotify  # Nothing requires async/await now!

Index

Installing

To install the library simply clone it and run pip.

  • git clone https://github.com/mental32/spotify.py
  • pip3 install -U .

or use pypi

  • pip3 install -U spotify (latest stable)
  • pip3 install -U git+https://github.com/mental32/spotify.py#egg=spotify (nightly)

Examples

Sorting a playlist by popularity

import sys
import getpass

import spotify

async def main():
    playlist_uri = input("playlist_uri: ")
    client_id = input("client_id: ")
    secret = getpass.getpass("application secret: ")
    token = getpass.getpass("user token: ")

    async with spotify.Client(client_id, secret) as client:
        user = await spotify.User.from_token(client, token)

        async for playlist in user:
            if playlist.uri == playlist_uri:
                return await playlist.sort(reverse=True, key=(lambda track: track.popularity))

        print('No playlists were found!', file=sys.stderr)

if __name__ == '__main__':
    client.loop.run_until_complete(main())

Required oauth scopes for methods

import spotify
from spotify.oauth import get_required_scopes

# In order to call this method sucessfully the "user-modify-playback-state" scope is required.
print(get_required_scopes(spotify.Player.play))  # => ["user-modify-playback-state"]

# Some methods have no oauth scope requirements, so `None` will be returned instead.
print(get_required_scopes(spotify.Playlist.get_tracks))  # => None

Usage with flask

import string
import random
from typing import Tuple, Dict

import flask
import spotify.sync as spotify

SPOTIFY_CLIENT = spotify.Client('SPOTIFY_CLIENT_ID', 'SPOTIFY_CLIENT_SECRET')

APP = flask.Flask(__name__)
APP.config.from_mapping({'spotify_client': SPOTIFY_CLIENT})

REDIRECT_URI: str = 'http://localhost:8888/spotify/callback'

OAUTH2_SCOPES: Tuple[str] = ('user-modify-playback-state', 'user-read-currently-playing', 'user-read-playback-state')
OAUTH2: spotify.OAuth2 = spotify.OAuth2(SPOTIFY_CLIENT.id, REDIRECT_URI, scopes=OAUTH2_SCOPES)

SPOTIFY_USERS: Dict[str, spotify.User] = {}


@APP.route('/spotify/callback')
def spotify_callback():
    try:
        code = flask.request.args['code']
    except KeyError:
        return flask.redirect('/spotify/failed')
    else:
        key = ''.join(random.choice(string.ascii_uppercase) for _ in range(16))
        SPOTIFY_USERS[key] = spotify.User.from_code(
            SPOTIFY_CLIENT,
            code,
            redirect_uri=REDIRECT_URI,
            refresh=True
        )

        flask.session['spotify_user_id'] = key

    return flask.redirect('/')

@APP.route('/spotify/failed')
def spotify_failed():
    flask.session.pop('spotify_user_id', None)
    return 'Failed to authenticate with Spotify.'

@APP.route('/')
@APP.route('/index')
def index():
    try:
        return repr(SPOTIFY_USERS[flask.session['spotify_user_id']])
    except KeyError:
        return flask.redirect(OAUTH2.url)

if __name__ == '__main__':
    APP.run('127.0.0.1', port=8888, debug=False)

Resources

For resources look at the examples or ask in the discord

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

spotify-0.9.0.tar.gz (39.1 kB view details)

Uploaded Source

Built Distribution

spotify-0.9.0-py3-none-any.whl (45.8 kB view details)

Uploaded Python 3

File details

Details for the file spotify-0.9.0.tar.gz.

File metadata

  • Download URL: spotify-0.9.0.tar.gz
  • Upload date:
  • Size: 39.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.43.0 CPython/3.8.2

File hashes

Hashes for spotify-0.9.0.tar.gz
Algorithm Hash digest
SHA256 460fc28a012c0bc027b18dc88ae52787ec47676a44c984c689966303851a45c7
MD5 a1f68a82acf37209392d7dec6713fd1c
BLAKE2b-256 f4ae9f3962c5fd86e45e3c3ec46adaa773b6534d4e0bf9fe8a1f29ac9a74b5ac

See more details on using hashes here.

File details

Details for the file spotify-0.9.0-py3-none-any.whl.

File metadata

  • Download URL: spotify-0.9.0-py3-none-any.whl
  • Upload date:
  • Size: 45.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/41.2.0 requests-toolbelt/0.9.1 tqdm/4.43.0 CPython/3.8.2

File hashes

Hashes for spotify-0.9.0-py3-none-any.whl
Algorithm Hash digest
SHA256 97ba915025d64ae112adaff6ec6a641e4828006e30c390a3fe6f98855f253bc4
MD5 a3645391623593fb8568ba44fc14d3e2
BLAKE2b-256 d29c4cbfa5cfa13265ff03ff0a3490eda3d03de46910c06085be0fe68fa1cf2b

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page