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.
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¶
Progress is stored only in this browser. You can skip to any example.
- Search for tracks
- Search from a synchronous script
- Reuse a catalogue client
- Normalize a Spotify link
- Inspect an album
- Export typed results to JSON
- Export public playlist metadata
- Read playlist occurrences
- Read your top tracks
Search for 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
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())
Step through the result
Synthetic offline test fixture; abbreviated model representation. No live request.
results = await Public.search(...)SearchResults(query='Daft Punk', tracks=(Track(...),))The fixture returns one track. The tuple can be empty.
results.tracks(Track(name='Fixture track', uri='spotify:track:33XUHrCbrAW6me9ewdCZip'),)Iterating the tuple makes no extra request.
print(track.name, track.uri)Fixture track spotify:track:33XUHrCbrAW6me9ewdCZipThe script prints one line for this fixture.
The offline fixture contains one matching track. How many lines does the loop print?
Give SpotAPI a GitHub star if this helped you; stars make useful projects easier to discover. Ask about adapting this script on Discord.
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.
Search from a 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
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()
The offline fixture returns one track. The with block finishes normally. What happens to the client?
Give SpotAPI a GitHub star if this helped you; stars make useful projects easier to discover. Ask about adapting this script on Discord.
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
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())
The offline fixture returns no artists. Which branch runs before any artist lookup?
Give SpotAPI a GitHub star if this helped you; stars make useful projects easier to discover. Ask about adapting this script on Discord.
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.
Normalize a Spotify link¶
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
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()
The input is the URL in the script. Which URI is printed?
Give SpotAPI a GitHub star if this helped you; stars make useful projects easier to discover. Ask about adapting this script on Discord.
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
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())
Step through the result
Synthetic offline test fixture; abbreviated model representation. No live request.
album = await Public.get_album(...)AlbumDetails(name='Fixture album', date=ReleaseDate('2013-01-01'), ...)The model contains the returned metadata.
album.date.year2013The year is derived from the fixture date.
print(album.name, album.uri, album.date.year)Fixture album spotify:album:4aawyAB9vmqN3uQ7FjRGTy 2013No additional network call is needed.
The offline album fixture uses the date 2013-01-01. What value is printed for album.date.year?
Give SpotAPI a GitHub star if this helped you; stars make useful projects easier to discover. Ask about adapting this script on Discord.
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
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())
The offline fixture contains one track. What does len(to_dict(results)['tracks']) return?
Give SpotAPI a GitHub star if this helped you; stars make useful projects easier to discover. Ask about adapting this script on Discord.
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
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())
The fixture playlist is named Fixture playlist. Which expression reads the exported name?
Give SpotAPI a GitHub star if this helped you; stars make useful projects easier to discover. Ask about adapting this script on Discord.
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
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())
Step through the result
Synthetic offline test fixture; abbreviated model representation. No live request.
async with aclosing(Public.iter_playlist_items(playlist)) as entries:async generator of PlaylistEntry objectsThe fixture yields 25 entries; the script stops after 20.
print(position, entry.uid, entry.uri or 'Unavailable')1 0 spotify:track:33XUHrCbrAW6me9ewdCZipThe occurrence UID is separate from the track URI.
entry.uri or 'Unavailable'2 1 UnavailableThe unavailable item retains its own position and UID.
if position == 20: break20 19 spotify:track:33XUHrCbrAW6me9ewdCZipaclosing 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?
Give SpotAPI a GitHub star if this helped you; stars make useful projects easier to discover. Ask about adapting this script on Discord.
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
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())
The offline fixture returns one top track. Which operation does this script perform?
Give SpotAPI a GitHub star if this helped you; stars make useful projects easier to discover. Ask about adapting this script on Discord.
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.
Understand the Python concepts used in the scripts.
Continue your examplesSpotAPI 2.1.3 · Source revision 56ae951 · Report a documentation issue · Identifier converter · Sponsor our documentation