Skip to content

Latest commit

 

History

History
679 lines (418 loc) · 24.1 KB

index.rst

File metadata and controls

679 lines (418 loc) · 24.1 KB

Welcome to Pyfy's documentation! 👋

Pyfy is a Sync + Async Pythonic Spotify Client that focuses on ease of use in personal projects and API stability and security for production grade codebases.

Setup 🥁

$ pip install pyfy

Quick Start 🎛️

Sync

from pyfy import Spotify

spt = Spotify('your_access_token')

spt.play()
spt.volume(85)
spt.next()
spt.pause()

Async

import asyncio
from pyfy import AsyncSpotify

spt = AsyncSpotify('your_access_token')

async def search():
    return await spt.search('A tout le monde')

search_result = asyncio.run(search())

Getting Started 👩

You should start by creating client credentials from Spotify's Developer's console.

Next, edit your application's settings and set a Redirect URL. If it's for personal use then set it as:

http://localhost:9000 Port can be any port of choice, not necessarily 9000

Next, copy your:

  1. Client ID
  2. Client Secret
  3. Redirect URL (That you just set)

Next, figure out the scopes that you think you'll need from here: https://developer.spotify.com/documentation/general/guides/scopes/

e.g. ["user-library-modify", "app-remote-control"]

Next, follow the first authentication scheme from below (it's the one you'll most likely need, unless you're sure otherwise)

Authentication 👩‍🎤

1. Authorization Code Flow (OAuth2) (recommended)

Suitable if you want to access user-related resources. e.g. user-playlists, user-tracks etc.

Click here for full working examples with Sanic(async) and Flask(sync).

from pyfy import Spotify, ClientCreds, UserCreds, AuthError, ApiError

client = ClientCreds(
    client_id='clientid',
    client_secret='client_secret',
    redirect_uri='https://localhost:9000",
    scopes=["user-library-modify", "app-remote-control"]
)
spt = Spotify(client_creds=client)

def authorize():
    # Fist step of OAuth, Redirect user to spotify's authorization endpoint
    if spt.is_oauth_ready:
        return redirect(spt.auth_uri())

# Authorization callback
def callback(grant):
    try:
        user_creds = spt.build_credentials(grant=grant)
    except AuthError as e:
        abort(401)
        logging.info(e.msg)
        logging.info(e.http_response)
    else:
        db.insert(user_creds)
        return redirect(url_for_home)

def get_user_tracks():
    try:
        return json.dumps(spt.user_tracks())
    except ApiError:
        abort(500)

2. User's Access Token: get from here

Same as the Authorization Code Flow above but without a refresh token. Suitable for quick runs.

from pyfy import Spotify

spt = Spotify('your access token')

3. Client Credentials Flow (OAuth2): get from here

Suitable for when you want to access public information quickly. (Accessing user information is porhibited using this method)

from pyfy import ClientCreds, Spotify

client = ClientCreds(client_id=client_id, client_secret=client_secret)
spt = Spotify(client_creds=client)
spt.authorize_client_creds()

API endpoints 🌐

Albums

Artists

Browse

Episodes

Follow

User Library

Personalization

Player

Playlists

Shows

Tracks

Users Profile

Pagination 📖

from pyfy import Spotify

user_creds = {'access_token': '...', 'refresh_token': '....'}

spt = Spotify(user_creds=user_creds)

user_top_tracks = spt.user_top_tracks(limit=5)

next_page_1 = spt.next_page(user_top_tracks)
next_page_2 = spt.next_page(next_page_1)

previous_page_1 = spt.previous_page(next_page_2)
previous_page_1 === next_page_1  # True

Sync Client API 🎸

pyfy.sync_client.Spotify

Async Client API 🎼

pyfy.sync_client.Spotify

Exceptions API ⚠️

pyfy.excs

Credentials API 📇

pyfy.creds

Testing 👩‍🔬

Unit tests

$ tox

Integration tests

  1. Open tox.ini and change thoee values to:

    1. SPOTIFY_CLIENT_ID Create an app
    2. SPOTIFY_CLIENT_SECRET Create an app
    3. SPOTIFY_ACCESS_TOKEN Get one or perform OAuth2 Auth Code Flow.

      Note

      Check all scopes when getting an access token.

    4. SPOTIFY_REFRESH_TOKEN

      Note

      To avoid manually refreshing your access token from the dev console, run the Oauth2 example in the examples dir. Then copy and paste the refresh token returned to your tox file.

    5. SPOTIFY_REDIRECT_URI = 'http://localhost:5000/callback/spotify'

      Note

      You have to register this callback in your Application's dashboard https://developer.spotify.com/dashboard/applications

    6. PYFY_TEST_INTEGRATION_SYNC` = true
    7. PYFY_TEST_INTEGRATION_ASYNC = true
  2. Run:

    Note

    • This will run some tests using your client ID, client secret and access token.
    • Unfortunately Spotify does not have a sandbox API, so we have to test it against the live API
    • Tests will carefully teardown all resources created and/or modified
    • Integration tests will not be abusive to the API and should only test for successful integration with minimum API calls
    • OAuth2 flow isn't tested in the tests folder (yet). Instead you can manually test it in the examples folder by running: pip install flask pyfy && python examples/oauth2.py
    $ tox

Indices and tables

  • genindex
  • modindex
  • search