Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@
installed optional packages; verify the headless-backend failure explicitly.
- Keep the v2.1.2 GitHub tag as a historical failed publishing attempt. Its
tagged workflow failed before uploading to PyPI; v2.1.3 supersedes it.
- Fix `get_album` failing with `AlbumDetails.pre_release_end_date_time: value
does not match str | None`: Spotify returns `preReleaseEndDateTime` as an
`{isoString, precision}` object, now decoded as `ReleaseDate`. Album search
hits shared the same field and were silently skipped; they decode too.
`ReleaseDate` now lives in `spotapi.models.catalogue.common`.

## 2.1.2 - 2026-11-22 (GitHub tag; PyPI publication blocked)

Expand Down
1 change: 1 addition & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ authenticated session.
| What you're building | Example | Notes |
|---|---|---|
| First public search | [public_search.py](public_search.py) | Typed results and predictable field names |
| Album lookup with pre-release end date | [album_lookup.py](album_lookup.py) | Prints name, pre-release end date and track count for one album |
| CSV audit of a large public playlist | [playlist_audit.py](playlist_audit.py) | Keeps duplicate occurrences and unavailable entries; bounded to 10,000 |
| Playlist overlap analysis | [overlap.py](overlap.py) | Compare shared tracks without editing either playlist |
| Artist and recording credits | [credit_trail.py](credit_trail.py) | Inspect contributors and related metadata |
Expand Down
18 changes: 18 additions & 0 deletions examples/album_lookup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"""Look up an album and print its pre-release end date and track count."""

import asyncio

from spotapi import Public


async def main() -> None:
album = await Public.get_album("spotify:album:3LUcDBe7DZDExhHbZEQchk")
end = album.pre_release_end_date_time

print(album.name)
print("Pre-release end:", end.iso_string if end else None, end.precision if end else None)
print("Tracks:", album.tracks_v2.total_count if album.tracks_v2 else len(album.tracks))


if __name__ == "__main__":
asyncio.run(main())
4 changes: 2 additions & 2 deletions spotapi/models/catalogue/album.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from dataclasses import dataclass, field

from .common import CoverArt, VisualIdentity
from .common import CoverArt, ReleaseDate, VisualIdentity

__all__ = ("Album",)

Expand Down Expand Up @@ -54,7 +54,7 @@ class Album:
date: Date | None = None
is_album_pre_release: bool | None = None
playability: Playability | None = None
pre_release_end_date_time: str | None = None
pre_release_end_date_time: ReleaseDate | None = None
type: str | None = None
visual_identity: VisualIdentity | None = None

Expand Down
14 changes: 2 additions & 12 deletions spotapi/models/catalogue/album_details.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
Playability as AlbumPlayability,
)
from .common import (
ReleaseDate,
Sources,
VisualIdentity,
)
Expand All @@ -34,17 +35,6 @@
__all__ = ("AlbumDetails",)


@dataclass(slots=True)
class ReleaseDate:
iso_string: str
precision: str | None = None

@property
def year(self) -> int:
"""Return the available release year without inventing an unknown date."""
return int(self.iso_string[:4])


@dataclass(slots=True)
class ArtistSharingInfo:
share_url: str | None = None
Expand Down Expand Up @@ -200,7 +190,7 @@ class AlbumDetails:
type: str | None = None
visual_identity: VisualIdentity | None = None
more_albums_by_artist: MoreAlbumsByArtist | None = None
pre_release_end_date_time: str | None = None
pre_release_end_date_time: ReleaseDate | None = None
releases: AlbumReleases | None = None
watch_feed_entrypoint: dict[str, Any] | None = None

Expand Down
16 changes: 15 additions & 1 deletion spotapi/models/catalogue/common.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Shared artwork and color dataclasses."""
"""Shared artwork, color and release-date dataclasses."""

from __future__ import annotations

Expand All @@ -11,12 +11,26 @@
"CoverArt",
"ExtractedColorSet",
"ExtractedColors",
"ReleaseDate",
"Sources",
"SquareCoverImage",
"VisualIdentity",
)


@dataclass(slots=True)
class ReleaseDate:
"""A Spotify timestamp: an ISO 8601 string and its precision (e.g. ``DAY``)."""

iso_string: str
precision: str | None = None

@property
def year(self) -> int:
"""Return the available release year without inventing an unknown date."""
return int(self.iso_string[:4])


@dataclass(slots=True)
class Sources:
"""One artwork URL with optional pixel dimensions; no image data is fetched."""
Expand Down
3 changes: 1 addition & 2 deletions spotapi/models/catalogue/entities.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@

from dataclasses import dataclass, field

from .album_details import ReleaseDate
from .common import CoverArt
from .common import CoverArt, ReleaseDate
from .podcast import Publisher
from .podcast_episode import EpisodePodcastReference
from .track import Duration
Expand Down
3 changes: 1 addition & 2 deletions spotapi/models/catalogue/podcast_episode.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@

from dataclasses import dataclass, field

from .album_details import ReleaseDate
from .common import Sources, VisualIdentity
from .common import ReleaseDate, Sources, VisualIdentity
from .track import ContentRating, Duration
from .track_details import SharingInfo

Expand Down
116 changes: 116 additions & 0 deletions tests/fixtures/catalogue/get_album_pre_release_end_date.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
{
"albumUnion": {
"__typename": "Album",
"copyright": {
"items": [
{"text": "2026 Prophecy Productions", "type": "C"},
{"text": "2026 Prophecy Productions", "type": "P"}
],
"totalCount": 2
},
"courtesyLine": "",
"date": {"isoString": "2026-02-20T00:00:00Z", "precision": "DAY"},
"isPreRelease": false,
"label": "Prophecy Productions",
"name": "Aba Khan",
"playability": {"playable": true, "reason": "PLAYABLE"},
"preReleaseEndDateTime": {"isoString": "2026-02-20T05:00:00Z", "precision": "MINUTE"},
"saved": false,
"sharingInfo": {
"shareId": "k6pVxV-MSCGXR45wyOMiqQ",
"shareUrl": "https://open.spotify.com/album/3LUcDBe7DZDExhHbZEQchk?si=k6pVxV-MSCGXR45wyOMiqQ"
},
"tracksV2": {
"items": [
{
"track": {
"artists": {
"items": [
{
"profile": {"name": "Nytt Land"},
"uri": "spotify:artist:6NQ701XGEJodDZ5lqVtrBp"
}
]
},
"associationsV3": {
"audioAssociations": {"totalCount": 0},
"videoAssociations": {"totalCount": 0}
},
"contentRating": {"label": "NONE"},
"discNumber": 1,
"duration": {"totalMilliseconds": 142235},
"mediaType": "AUDIO",
"name": "Aba Khan",
"playability": {"playable": true},
"playcount": "15313",
"relinkingInformation": null,
"saved": false,
"trackNumber": 1,
"uri": "spotify:track:5GZeWg8JmrxO15G2KT6p9p"
},
"uid": "4772f4dc743d57837fc3"
},
{
"track": {
"artists": {
"items": [
{
"profile": {"name": "Nytt Land"},
"uri": "spotify:artist:6NQ701XGEJodDZ5lqVtrBp"
}
]
},
"associationsV3": {
"audioAssociations": {"totalCount": 0},
"videoAssociations": {"totalCount": 0}
},
"contentRating": {"label": "NONE"},
"discNumber": 1,
"duration": {"totalMilliseconds": 405882},
"mediaType": "AUDIO",
"name": "Taiga",
"playability": {"playable": true},
"playcount": "38060",
"relinkingInformation": null,
"saved": false,
"trackNumber": 2,
"uri": "spotify:track:3Gt2s4m4yw7NDPPFgJpf5O"
},
"uid": "6c7375030f2f3c35a3b4"
}
],
"totalCount": 8
},
"type": "ALBUM",
"uri": "spotify:album:3LUcDBe7DZDExhHbZEQchk",
"watchFeedEntrypoint": null,
"artists": {
"items": [
{
"id": "6NQ701XGEJodDZ5lqVtrBp",
"profile": {"name": "Nytt Land"},
"sharingInfo": {
"shareUrl": "https://open.spotify.com/artist/6NQ701XGEJodDZ5lqVtrBp?si=7Nf73ATjT6aRAASmy0QHFQ"
},
"uri": "spotify:artist:6NQ701XGEJodDZ5lqVtrBp"
}
],
"totalCount": 1
},
"coverArt": {
"extractedColors": {"colorDark": {"hex": "#600810"}},
"sources": [
{
"height": 300,
"url": "https://i.scdn.co/image/ab67616d00001e02798cbc922f80394af87cef8c",
"width": 300
}
]
},
"discs": {
"items": [{"number": 1, "tracks": {"totalCount": 8}}],
"totalCount": 1
}
},
"meV2": {"ianaTimezoneId": "America/New_York"}
}
103 changes: 103 additions & 0 deletions tests/test_album_pre_release.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
"""Regression tests for ``preReleaseEndDateTime`` objects in album payloads.

Spotify returns this field as ``{"isoString": ..., "precision": ...}`` even when
``isPreRelease`` is false. It once failed with ``getAlbum: failed to deserialize
AlbumDetails: AlbumDetails.pre_release_end_date_time: value does not match
str | None``.
"""

from __future__ import annotations

import json
from pathlib import Path
from typing import Any

import pytest

from spotapi.datastruct import ObjectDict
from spotapi.models.catalogue import Album, AlbumDetails, from_dict
from spotapi.models.catalogue.common import ReleaseDate
from spotapi.operations import Operations
from spotapi.queries import Queries

ALBUM_URI = "spotify:album:3LUcDBe7DZDExhHbZEQchk"
FIXTURE = Path(__file__).parent / "fixtures" / "catalogue" / "get_album_pre_release_end_date.json"


def _album_response() -> dict[str, Any]:
"""Load the sanitized, trimmed getAlbum response for the Nytt Land album."""
return json.loads(FIXTURE.read_text(encoding="utf-8"))


async def _get_album(response: dict[str, Any], monkeypatch: pytest.MonkeyPatch) -> AlbumDetails:
async def direct_query(self: Queries, uri: str, /, operation: Operations) -> ObjectDict:
assert (uri, operation) == (ALBUM_URI, Operations.GET_ALBUM)

return ObjectDict(response)

monkeypatch.setattr(Queries, "direct_query", direct_query)

return await Queries().resource(ALBUM_URI, Operations.GET_ALBUM, AlbumDetails)


async def test_get_album_decodes_object_pre_release_end_date(
monkeypatch: pytest.MonkeyPatch,
) -> None:
album = await _get_album(_album_response(), monkeypatch)

assert album.is_pre_release is False
assert album.pre_release_end_date_time == ReleaseDate(
iso_string="2026-02-20T05:00:00Z", precision="MINUTE"
)
assert album.name == "Aba Khan"
assert [track.name for track in album.tracks] == ["Aba Khan", "Taiga"]


@pytest.mark.parametrize("precision", ["DAY", "MINUTE"])
async def test_get_album_accepts_either_pre_release_precision(
precision: str, monkeypatch: pytest.MonkeyPatch
) -> None:
response = _album_response()
response["albumUnion"]["preReleaseEndDateTime"] = {
"isoString": "2026-02-20T00:00:00Z",
"precision": precision,
}

album = await _get_album(response, monkeypatch)

assert album.pre_release_end_date_time is not None
assert album.pre_release_end_date_time.precision == precision
assert album.pre_release_end_date_time.year == 2026


@pytest.mark.parametrize("missing", [False, True])
async def test_get_album_keeps_pre_release_end_date_optional(
missing: bool, monkeypatch: pytest.MonkeyPatch
) -> None:
response = _album_response()

if missing:
del response["albumUnion"]["preReleaseEndDateTime"]
else:
response["albumUnion"]["preReleaseEndDateTime"] = None

album = await _get_album(response, monkeypatch)

assert album.pre_release_end_date_time is None


def test_album_search_hit_decodes_object_pre_release_end_date() -> None:
"""Search skips undecodable hits, so a mismatch would silently drop the album."""
album = from_dict(
Album,
{
"name": "Aba Khan",
"uri": ALBUM_URI,
"isAlbumPreRelease": False,
"preReleaseEndDateTime": {"isoString": "2026-02-20T05:00:00Z", "precision": "MINUTE"},
},
)

assert album.pre_release_end_date_time == ReleaseDate(
iso_string="2026-02-20T05:00:00Z", precision="MINUTE"
)