Skip to content
SpotAPI / Copy-and-run examples PyPI 2.1.3 · source 56ae951 · Python 3.11+ Guides follow post-release source. Install the documented revision.

Copy-and-run examples

Complete Python 3.11+ scripts. Install SpotAPI once, then copy or download an example and run it locally. Public examples need no developer API key.

Installation

Start with the published wheel in a virtual environment. The nine downloadable scripts passed offline contract tests against PyPI 2.1.3.

Install the tested release
python -m pip install spotapi==2.1.3
Using the exact documentation source?

The guides and generated reference follow post-release main revision 56ae951. For that exact API, install git+https://github.com/Aran404/SpotAPI.git@56ae95116bd7434356d9c6ec392704ef382e07ca with pip. The wheel and source are checked separately.

Examples are exercised against the pinned library with controlled responses. Network examples make real requests when run; availability and results depend on Spotify.

Install the documented version in a virtual environment. Authentication examples use your own account only; never enter a session cookie on this website.

Already comfortable with Python? Build a playlist duplicate analyzer with an offline fixture and JSON report.

Your route through the examples

0 of 9 predictions answered ·

Progress is stored only in this browser. You can skip to any example.

  1. Search for tracks
  2. Search from a synchronous script
  3. Reuse a catalogue client
  4. Normalize a Spotify link
  5. Inspect an album
  6. Export typed results to JSON
  7. Export public playlist metadata
  8. Read playlist occurrences
  9. Read your top tracks

Example 1 of 9 · Public · Async

Run this script to print the names and URIs of up to five matching tracks. A successful search may return an empty collection. Use the fixture below to inspect the response before contacting Spotify.

Expected output: One line per returned track: its name followed by its Spotify URI.

Public owns and closes its temporary client. Await suspends the coroutine while it waits for the request. Accessing the returned track fields does not fetch more data.

Concepts: Async request · Client ownership · Typed result

Download search.py · Read the guide

search.py
import asyncio
from spotapi import Public


async def main() -> None:
    results = await Public.search("Daft Punk", types="track", limit=5)
    for track in results.tracks:
        print(track.name, track.uri)


if __name__ == "__main__":
    asyncio.run(main())
Run locally
python search.py

Step through the result

Synthetic offline test fixture; abbreviated model representation. No live request.

Await the request
results = await Public.search(...)
SearchResults(query='Daft Punk', tracks=(Track(...),))

The fixture returns one track. The tuple can be empty.

Inspect the collection
results.tracks
(Track(name='Fixture track', uri='spotify:track:33XUHrCbrAW6me9ewdCZip'),)

Iterating the tuple makes no extra request.

Print one track
print(track.name, track.uri)
Fixture track spotify:track:33XUHrCbrAW6me9ewdCZip

The script prints one line for this fixture.

The offline fixture contains one matching track. How many lines does the loop print?

One. The fixture contains one track. The limit of five caps the number returned.

Next: Search from a synchronous script. Compare the same request in a normal synchronous script.

Example 2 of 9 · Public · Sync

Use this in a plain Python script when you do not need an asynchronous application. For an existing event loop, use the async version.

Expected output: Track names and URIs from a synchronous script.

SyncCatalogue owns an event loop and closes its client when the with block exits.

Concepts: Client ownership · Async request

Download sync_search.py · Read the guide

sync_search.py
from spotapi import SyncCatalogue


def main() -> None:
    with SyncCatalogue() as spotify:
        results = spotify.search("Daft Punk", types="track", limit=5)
        for track in results.tracks:
            print(track.name, track.uri)


if __name__ == "__main__":
    main()
Run locally
python sync_search.py
The offline fixture returns one track. The with block finishes normally. What happens to the client?

The context closes it. The synchronous context manager owns cleanup. The fixture tests __exit__.

Next: Reuse a catalogue client. Reuse a client for more than one request.

Reuse a catalogue client

Example 3 of 9 · Public · Async

Search for artists, then fetch details for the first match through the same Catalogue context. This is the pattern I would use for several related calls.

Expected output: The name of the first matching artist, or a no-match message.

A Catalogue context keeps client ownership explicit. Reusing a scope also avoids repeatedly setting up clients.

Concepts: Client ownership · Typed result

Download catalogue.py · Read the guide

catalogue.py
import asyncio
from spotapi import Catalogue


async def main() -> None:
    async with Catalogue() as spotify:
        results = await spotify.search("Daft Punk", types="artist", limit=5)
        if results.artists:
            artist = await spotify.get_artist(results.artists[0].uri)
            print(artist.name)
        else:
            print("No matching artist.")


if __name__ == "__main__":
    asyncio.run(main())
Run locally
python catalogue.py
The offline fixture returns no artists. Which branch runs before any artist lookup?

The no-match branch. The example checks the collection before indexing it; there is no artist lookup when the collection is empty.

Next: Normalize a Spotify link. Normalize an identifier before using it in a request.

Example 4 of 9 · Offline · Sync

Clean a Spotify share link locally. This is useful before calling the API, and it needs neither a session nor a network connection.

Expected output: The resource kind, canonical URI and share URL.

A normalized identifier tells you which resource is requested. It cannot establish existence or permissions.

Concepts: Resource identity

Download parse_link.py · Read the guide

parse_link.py
from spotapi import Public


def main() -> None:
    resource = Public.parse_url(
        "https://open.spotify.com/track/33XUHrCbrAW6me9ewdCZip"
    )
    print(resource.kind, resource.uri, resource.url)


if __name__ == "__main__":
    main()
Run locally
python parse_link.py
The input is the URL in the script. Which URI is printed?

spotify:track:33XUHrCbrAW6me9ewdCZip. The track path determines the resource kind; the identifier is unchanged.

Next: Inspect an album. Use a resource identifier to retrieve an actual album.

Inspect an album

Example 5 of 9 · Public · Async

Read an album's title and release year. Replace the URI with one from your own application.

Expected output: Album title, Spotify URI and release year.

AlbumDetails is typed metadata. The date's year is available on the returned object without an extra request.

Concepts: Resource identity · Typed result

Download album.py · Read the guide

album.py
import asyncio
from spotapi import Public


async def main() -> None:
    album = await Public.get_album("spotify:album:4aawyAB9vmqN3uQ7FjRGTy")
    print(album.name, album.uri, album.date.year)


if __name__ == "__main__":
    asyncio.run(main())
Run locally
python album.py

Step through the result

Synthetic offline test fixture; abbreviated model representation. No live request.

Request album details
album = await Public.get_album(...)
AlbumDetails(name='Fixture album', date=ReleaseDate('2013-01-01'), ...)

The model contains the returned metadata.

Read its date
album.date.year
2013

The year is derived from the fixture date.

Print the fields
print(album.name, album.uri, album.date.year)
Fixture album spotify:album:4aawyAB9vmqN3uQ7FjRGTy 2013

No additional network call is needed.

The offline album fixture uses the date 2013-01-01. What value is printed for album.date.year?

2013. The year property extracts the year from the returned date.

Next: Export typed results to JSON. Convert the returned Python objects to a portable format.

Export typed results to JSON

Example 6 of 9 · Public · Async

Save the result from a public track search as JSON. Select only the fields you need before sharing an export containing account data.

Expected output: A JSON object containing the requested categories and their typed results.

to_dict transforms typed results to plain values. json.dumps then serializes those values.

Concepts: Typed result

Download export.py · Read the guide

export.py
import asyncio
import json
from spotapi import Public, to_dict


async def main() -> None:
    results = await Public.search("Daft Punk", types="track", limit=5)
    print(json.dumps(to_dict(results), indent=2))


if __name__ == "__main__":
    asyncio.run(main())
Run locally
python export.py
The offline fixture contains one track. What does len(to_dict(results)['tracks']) return?

1. The serializer preserves the collection of returned tracks; it does not pad the result to the requested limit.

Next: Export public playlist metadata. Apply serialization to playlist metadata.

Export public playlist metadata

Example 7 of 9 · Public · Async

Export the metadata of an accessible public playlist. To obtain its contents, use the separate occurrence iterator.

Expected output: JSON containing the playlist's available metadata.

A playlist object and its individual entries represent different levels of data.

Concepts: Occurrence identity · Typed result

Download playlist_export.py · Read the guide

playlist_export.py
import asyncio
import json
from spotapi import Public, to_dict


async def main() -> None:
    playlist = await Public.get_playlist("37i9dQZF1DXcBWIGoYBM5M")
    print(json.dumps(to_dict(playlist), indent=2))


if __name__ == "__main__":
    asyncio.run(main())
Run locally
python playlist_export.py
The fixture playlist is named Fixture playlist. Which expression reads the exported name?

data['name']. The serializer returns the playlist's top-level fields. Its name is a top-level value.

Next: Read playlist occurrences. Iterate entries without losing duplicates or unavailable items.

Read playlist occurrences

Example 8 of 9 · Public · Async

Print the first 20 playlist occurrences, including unavailable entries. Preserve occurrence IDs when auditing repeated songs.

Expected output: Position, occurrence ID and URI, or an unavailable-entry marker.

Two occurrences may refer to the same track. aclosing ensures that stopping the loop early closes the generator.

Concepts: Occurrence identity · Client ownership

Download playlist_preview.py · Read the guide

playlist_preview.py
import asyncio
from contextlib import aclosing
from spotapi import Public


async def main() -> None:
    playlist = "37i9dQZF1DXcBWIGoYBM5M"
    async with aclosing(Public.iter_playlist_items(playlist)) as entries:
        position = 0
        async for entry in entries:
            position += 1
            print(position, entry.uid, entry.uri or "Unavailable")
            if position == 20:
                break


if __name__ == "__main__":
    asyncio.run(main())
Run locally
python playlist_preview.py

Step through the result

Synthetic offline test fixture; abbreviated model representation. No live request.

Start the iterator
async with aclosing(Public.iter_playlist_items(playlist)) as entries:
async generator of PlaylistEntry objects

The fixture yields 25 entries; the script stops after 20.

Read the first occurrence
print(position, entry.uid, entry.uri or 'Unavailable')
1 0 spotify:track:33XUHrCbrAW6me9ewdCZip

The occurrence UID is separate from the track URI.

Handle the missing item
entry.uri or 'Unavailable'
2 1 Unavailable

The unavailable item retains its own position and UID.

Break at the twentieth occurrence
if position == 20: break
20 19 spotify:track:33XUHrCbrAW6me9ewdCZip

aclosing closes the generator when the loop stops.

The offline test fixture has 25 occurrences. The second is unavailable. How many lines does the script print?

20. The loop prints each occurrence, including the unavailable one, then breaks at position 20.

Next: Read your top tracks. Move from public data to a read-only request for your own account.

Read your top tracks

Example 9 of 9 · Own account · Read-only

Read your own listening rankings. Keep the session cookie in the environment and out of code, screenshots and issue reports.

Expected output: Up to five track names and URIs from your medium-term affinity ranking.

Private opens an authenticated scope. It must use credentials for an account you are authorized to access.

Concepts: Account scope · Typed result

Download favorites.py · Read the guide

favorites.py
import asyncio
import os
from spotapi import Private


async def main() -> None:
    async with Private.from_cookies(os.environ["SPOTIFY_COOKIE"]) as account:
        favorites = await account.stats.get(time_range="medium_term", limit=5)
        for track in favorites.tracks:
            print(track.name, track.uri)


if __name__ == "__main__":
    asyncio.run(main())
Run locally
python favorites.py
The offline fixture returns one top track. Which operation does this script perform?

Reads the track ranking. The stats request is read-only. The fixture checks the time range and requested limit.

Next: Account guide. Review authentication and account boundaries before extending this script.

SpotAPI 2.1.3 · Source revision 56ae951 · Report a documentation issue · Identifier converter · Sponsor our documentation