A light weight Python library for the Spotify Web API
npx @tessl/cli install tessl/pypi-spotipy@2.25.00
# Spotipy
1
2
A lightweight Python library for the Spotify Web API that provides comprehensive access to all Spotify endpoints. Spotipy handles authentication, rate limiting, and provides a clean Pythonic interface for integrating Spotify's music data and services into applications.
3
4
## Package Information
5
6
- **Package Name**: spotipy
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install spotipy`
10
11
## Core Imports
12
13
```python
14
import spotipy
15
from spotipy.oauth2 import SpotifyClientCredentials, SpotifyOAuth
16
```
17
18
## Basic Usage
19
20
### Client Credentials Flow (App-only access)
21
22
```python
23
import spotipy
24
from spotipy.oauth2 import SpotifyClientCredentials
25
26
# Initialize client
27
client_credentials_manager = SpotifyClientCredentials(
28
client_id="YOUR_CLIENT_ID",
29
client_secret="YOUR_CLIENT_SECRET"
30
)
31
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)
32
33
# Search for tracks
34
results = sp.search(q='artist:radiohead', type='track', limit=10)
35
for track in results['tracks']['items']:
36
print(track['name'], '-', track['artists'][0]['name'])
37
```
38
39
### Authorization Code Flow (User authentication)
40
41
```python
42
import spotipy
43
from spotipy.oauth2 import SpotifyOAuth
44
45
# Initialize with user authentication
46
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(
47
client_id="YOUR_CLIENT_ID",
48
client_secret="YOUR_CLIENT_SECRET",
49
redirect_uri="YOUR_REDIRECT_URI",
50
scope="user-library-read user-read-playback-state"
51
))
52
53
# Access user's saved tracks
54
results = sp.current_user_saved_tracks(limit=50)
55
for item in results['items']:
56
track = item['track']
57
print(f"{track['name']} by {track['artists'][0]['name']}")
58
```
59
60
## Architecture
61
62
Spotipy follows a modular architecture with clear separation of concerns:
63
64
- **Spotify Client**: Core API client handling all Spotify Web API endpoints
65
- **Authentication Managers**: OAuth2 flows (Client Credentials, Authorization Code, PKCE, Implicit Grant)
66
- **Cache Handlers**: Token persistence across sessions (File, Memory, Redis, Memcache, Django, Flask)
67
- **Exception Handling**: Structured error handling for API and OAuth errors
68
- **Utilities**: Helper functions for scope management and URL parsing
69
70
## Capabilities
71
72
### Core API Client
73
74
The main Spotify client providing access to all Spotify Web API endpoints including search, tracks, albums, artists, playlists, user data, and playback control.
75
76
```python { .api }
77
class Spotify:
78
def __init__(self, auth=None, requests_session=True, client_credentials_manager=None,
79
oauth_manager=None, auth_manager=None, proxies=None, requests_timeout=5,
80
status_forcelist=None, retries=3, status_retries=3, backoff_factor=0.3,
81
language=None):
82
"""Initialize Spotify client with authentication and configuration."""
83
84
def search(self, q, limit=10, offset=0, type="track", market=None):
85
"""Search for tracks, albums, artists, playlists, shows, episodes, or audiobooks."""
86
87
def track(self, track_id, market=None):
88
"""Get Spotify track information."""
89
90
def album(self, album_id, market=None):
91
"""Get Spotify album information."""
92
93
def artist(self, artist_id):
94
"""Get Spotify artist information."""
95
```
96
97
[Core API Client](./client.md)
98
99
### Authentication and Authorization
100
101
OAuth2 authentication flows for both app-only and user authentication scenarios, supporting multiple flow types with comprehensive token management.
102
103
```python { .api }
104
class SpotifyClientCredentials:
105
def __init__(self, client_id=None, client_secret=None, proxies=None,
106
requests_session=True, requests_timeout=None, cache_handler=None):
107
"""Client Credentials flow for app-only authentication."""
108
109
class SpotifyOAuth:
110
def __init__(self, client_id=None, client_secret=None, redirect_uri=None,
111
state=None, scope=None, cache_path=None, username=None,
112
proxies=None, requests_session=True, show_dialog=False,
113
requests_timeout=None, open_browser=True, cache_handler=None):
114
"""Authorization Code flow for user authentication."""
115
```
116
117
[Authentication](./authentication.md)
118
119
### User Library and Profile
120
121
Manage user's saved content including tracks, albums, shows, episodes, followed artists, and personal profile information.
122
123
```python { .api }
124
def current_user_saved_tracks(self, limit=20, offset=0, market=None):
125
"""Get user's saved tracks."""
126
127
def current_user_saved_albums(self, limit=20, offset=0, market=None):
128
"""Get user's saved albums."""
129
130
def current_user_followed_artists(self, limit=20, after=None):
131
"""Get user's followed artists."""
132
133
def me(self):
134
"""Get current user's profile."""
135
```
136
137
[User Library and Profile](./user-library.md)
138
139
### Playlist Management
140
141
Comprehensive playlist operations including creation, modification, track management, and collaboration features.
142
143
```python { .api }
144
def playlist(self, playlist_id, fields=None, market=None, additional_types=("track",)):
145
"""Get playlist information."""
146
147
def playlist_add_items(self, playlist_id, items, position=None):
148
"""Add tracks or episodes to playlist."""
149
150
def playlist_change_details(self, playlist_id, name=None, public=None,
151
collaborative=None, description=None):
152
"""Change playlist details."""
153
```
154
155
[Playlist Management](./playlists.md)
156
157
### Playback Control
158
159
Control Spotify playback across user's devices including play/pause, track navigation, volume, and queue management.
160
161
```python { .api }
162
def current_playback(self, market=None, additional_types=None):
163
"""Get current playback information."""
164
165
def start_playback(self, device_id=None, context_uri=None, uris=None,
166
offset=None, position_ms=None):
167
"""Start or resume playback."""
168
169
def pause_playback(self, device_id=None):
170
"""Pause playback."""
171
```
172
173
[Playback Control](./playback.md)
174
175
### Browse and Discover
176
177
Discovery features including featured playlists, new releases, categories, recommendations, and audio features analysis.
178
179
```python { .api }
180
def featured_playlists(self, country=None, locale=None, timestamp=None,
181
limit=20, offset=0):
182
"""Get featured playlists."""
183
184
def recommendations(self, seed_artists=None, seed_genres=None, seed_tracks=None,
185
limit=20, country=None, **kwargs):
186
"""Get track recommendations."""
187
188
def audio_features(self, tracks=[]):
189
"""Get audio features for tracks."""
190
```
191
192
[Browse and Discover](./browse.md)
193
194
### Podcasts and Shows
195
196
Access podcast shows, episodes, and audiobook content with comprehensive metadata and user library integration.
197
198
```python { .api }
199
def show(self, show_id, market=None):
200
"""Get show information."""
201
202
def episode(self, episode_id, market=None):
203
"""Get episode information."""
204
205
def get_audiobook(self, id, market=None):
206
"""Get audiobook information."""
207
```
208
209
[Podcasts and Shows](./podcasts.md)
210
211
### Cache Management and Utilities
212
213
Token caching strategies and utility functions for efficient session management and scope handling.
214
215
```python { .api }
216
class CacheFileHandler:
217
def __init__(self, cache_path=None, username=None, encoder_cls=None):
218
"""File-based token caching."""
219
220
class RedisCacheHandler:
221
def __init__(self, redis_instance=None, key=None, encoder_cls=None):
222
"""Redis-based token caching."""
223
```
224
225
[Cache Management](./cache.md)
226
227
## Error Handling
228
229
```python { .api }
230
class SpotifyException(Exception):
231
def __init__(self, http_status, code, msg, reason=None, headers=None):
232
"""General Spotify API exception with HTTP status and error details."""
233
234
class SpotifyOauthError(Exception):
235
def __init__(self, message, error=None, error_description=None, *args, **kwargs):
236
"""OAuth-related authentication errors."""
237
```
238
239
Common error scenarios include rate limiting (429), invalid tokens (401), insufficient scope permissions (403), and resource not found (404). All exceptions include detailed error information for debugging.