Skip to content
Merged
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
2 changes: 2 additions & 0 deletions src/spotifyaio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
SpotifyConnectionError,
SpotifyError,
SpotifyNotFoundError,
SpotifyRateLimitError,
)
from .models import (
Album,
Expand Down Expand Up @@ -68,6 +69,7 @@
"SpotifyConnectionError",
"SpotifyError",
"SpotifyNotFoundError",
"SpotifyRateLimitError",
"Track",
"UserProfile",
]
4 changes: 4 additions & 0 deletions src/spotifyaio/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,7 @@ class SpotifyAuthenticationFailedError(SpotifyError):

class SpotifyNotFoundError(SpotifyError):
"""Spotify not found exception."""


class SpotifyRateLimitError(SpotifyError):
"""Spotify rate limit exception."""
10 changes: 9 additions & 1 deletion src/spotifyaio/spotify.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@
import orjson
from yarl import URL

from spotifyaio.exceptions import SpotifyConnectionError, SpotifyNotFoundError
from spotifyaio.exceptions import (
SpotifyConnectionError,
SpotifyNotFoundError,
SpotifyRateLimitError,
)
from spotifyaio.models import (
Album,
AlbumsResponse,
Expand Down Expand Up @@ -132,6 +136,10 @@ async def _request(
msg = f"Resource not found: {uri}"
raise SpotifyNotFoundError(msg)

if '"status": 429' in text:
msg = "Ratelimit exceeded"
raise SpotifyRateLimitError(msg)

return text

async def _get(self, uri: str, params: dict[str, Any] | None = None) -> str:
Expand Down
6 changes: 6 additions & 0 deletions tests/fixtures/rate_limit.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"error": {
"status": 429,
"message": "API rate limit exceeded"
}
}
18 changes: 18 additions & 0 deletions tests/test_spotify.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
SpotifyClient,
SpotifyConnectionError,
SpotifyNotFoundError,
SpotifyRateLimitError,
)

from . import load_fixture
Expand Down Expand Up @@ -884,6 +885,23 @@ async def test_get_not_found_playlist(
await authenticated_client.get_playlist("37i9dQZF1DXcBWIGoYBM5M")


async def test_rate_limit(
responses: aioresponses,
authenticated_client: SpotifyClient,
) -> None:
"""Test raising rate limit exception."""
responses.get(
f"{SPOTIFY_URL}/v1/playlists/37i9dQZF1DXcBWIGoYBM5M?additional_types=track,episode",
status=200,
body=load_fixture("rate_limit.json"),
)
with pytest.raises(
SpotifyRateLimitError,
match="Ratelimit exceeded",
):
await authenticated_client.get_playlist("37i9dQZF1DXcBWIGoYBM5M")


@pytest.mark.parametrize(
"fixture",
[
Expand Down