0
# Core API Client
1
2
The Spotify class is the main client providing access to all Spotify Web API endpoints. It handles authentication, rate limiting, pagination, and provides a comprehensive Python interface for all Spotify services.
3
4
## Capabilities
5
6
### Client Initialization
7
8
Initialize the Spotify client with various authentication and configuration options.
9
10
```python { .api }
11
class Spotify:
12
def __init__(self, auth=None, requests_session=True, client_credentials_manager=None,
13
oauth_manager=None, auth_manager=None, proxies=None, requests_timeout=5,
14
status_forcelist=None, retries=3, status_retries=3, backoff_factor=0.3,
15
language=None):
16
"""
17
Initialize Spotify client.
18
19
Args:
20
auth (str, optional): Bearer token for authentication
21
requests_session (bool or requests.Session): HTTP session configuration
22
client_credentials_manager: Deprecated, use auth_manager
23
oauth_manager: Deprecated, use auth_manager
24
auth_manager: Authentication manager instance
25
proxies (dict, optional): Proxy configuration
26
requests_timeout (int): Request timeout in seconds (default: 5)
27
status_forcelist (list, optional): HTTP status codes to retry
28
retries (int): Number of retries (default: 3)
29
status_retries (int): Status-specific retries (default: 3)
30
backoff_factor (float): Backoff factor for retries (default: 0.3)
31
language (str, optional): Language for responses
32
"""
33
```
34
35
### Search Operations
36
37
Search across all Spotify content types with flexible filtering and pagination.
38
39
```python { .api }
40
def search(self, q, limit=10, offset=0, type="track", market=None):
41
"""
42
Search for content on Spotify.
43
44
Args:
45
q (str): Search query string
46
limit (int): Number of results to return (1-50, default: 10)
47
offset (int): Index of first result (default: 0)
48
type (str): Content type - 'track', 'album', 'artist', 'playlist', 'show', 'episode', 'audiobook'
49
market (str, optional): ISO 3166-1 alpha-2 country code
50
51
Returns:
52
dict: Search results with paging information
53
"""
54
55
def search_markets(self, q, limit=10, offset=0, type="track", markets=None, total=None):
56
"""
57
Search across multiple markets.
58
59
Args:
60
q (str): Search query string
61
limit (int): Number of results per market (1-50, default: 10)
62
offset (int): Index of first result (default: 0)
63
type (str): Content type to search for
64
markets (list, optional): List of market codes to search
65
total (int, optional): Total number of results to collect
66
67
Returns:
68
dict: Aggregated search results across markets
69
"""
70
```
71
72
### Track Operations
73
74
Access track information, audio features, and detailed audio analysis.
75
76
```python { .api }
77
def track(self, track_id, market=None):
78
"""
79
Get track information.
80
81
Args:
82
track_id (str): Spotify track ID or URI
83
market (str, optional): ISO 3166-1 alpha-2 country code
84
85
Returns:
86
dict: Track object with metadata
87
"""
88
89
def tracks(self, tracks, market=None):
90
"""
91
Get multiple tracks.
92
93
Args:
94
tracks (list): List of track IDs or URIs (max 50)
95
market (str, optional): ISO 3166-1 alpha-2 country code
96
97
Returns:
98
dict: Tracks object containing list of track objects
99
"""
100
101
def audio_features(self, tracks=[]):
102
"""
103
Get audio features for tracks.
104
105
Args:
106
tracks (list): List of track IDs or URIs (max 100)
107
108
Returns:
109
dict: Audio features objects with acousticness, danceability, energy, etc.
110
"""
111
112
def audio_analysis(self, track_id):
113
"""
114
Get detailed audio analysis for a track.
115
116
Args:
117
track_id (str): Spotify track ID or URI
118
119
Returns:
120
dict: Detailed audio analysis with bars, beats, sections, segments, tatums
121
"""
122
```
123
124
### Artist Operations
125
126
Access artist information, albums, top tracks, and related artists.
127
128
```python { .api }
129
def artist(self, artist_id):
130
"""
131
Get artist information.
132
133
Args:
134
artist_id (str): Spotify artist ID or URI
135
136
Returns:
137
dict: Artist object with metadata
138
"""
139
140
def artists(self, artists):
141
"""
142
Get multiple artists.
143
144
Args:
145
artists (list): List of artist IDs or URIs (max 50)
146
147
Returns:
148
dict: Artists object containing list of artist objects
149
"""
150
151
def artist_albums(self, artist_id, album_type=None, country=None, limit=20, offset=0):
152
"""
153
Get artist's albums.
154
155
Args:
156
artist_id (str): Spotify artist ID or URI
157
album_type (str, optional): Filter by album type - 'album', 'single', 'appears_on', 'compilation'
158
country (str, optional): ISO 3166-1 alpha-2 country code
159
limit (int): Number of albums to return (1-50, default: 20)
160
offset (int): Index of first album (default: 0)
161
162
Returns:
163
dict: Paging object of simplified album objects
164
"""
165
166
def artist_top_tracks(self, artist_id, country="US"):
167
"""
168
Get artist's top tracks in a country.
169
170
Args:
171
artist_id (str): Spotify artist ID or URI
172
country (str): ISO 3166-1 alpha-2 country code (default: "US")
173
174
Returns:
175
dict: Object containing list of track objects
176
"""
177
178
def artist_related_artists(self, artist_id):
179
"""
180
Get artists similar to a given artist.
181
182
Args:
183
artist_id (str): Spotify artist ID or URI
184
185
Returns:
186
dict: Object containing list of artist objects (max 20)
187
"""
188
```
189
190
### Album Operations
191
192
Access album information and track listings.
193
194
```python { .api }
195
def album(self, album_id, market=None):
196
"""
197
Get album information.
198
199
Args:
200
album_id (str): Spotify album ID or URI
201
market (str, optional): ISO 3166-1 alpha-2 country code
202
203
Returns:
204
dict: Album object with metadata and tracks
205
"""
206
207
def albums(self, albums, market=None):
208
"""
209
Get multiple albums.
210
211
Args:
212
albums (list): List of album IDs or URIs (max 20)
213
market (str, optional): ISO 3166-1 alpha-2 country code
214
215
Returns:
216
dict: Albums object containing list of album objects
217
"""
218
219
def album_tracks(self, album_id, limit=50, offset=0, market=None):
220
"""
221
Get tracks from an album.
222
223
Args:
224
album_id (str): Spotify album ID or URI
225
limit (int): Number of tracks to return (1-50, default: 50)
226
offset (int): Index of first track (default: 0)
227
market (str, optional): ISO 3166-1 alpha-2 country code
228
229
Returns:
230
dict: Paging object of simplified track objects
231
"""
232
```
233
234
### User Profile Operations
235
236
Access user profile information.
237
238
```python { .api }
239
def user(self, user):
240
"""
241
Get public profile information about a Spotify user.
242
243
Args:
244
user (str): Spotify user ID
245
246
Returns:
247
dict: User profile object
248
"""
249
250
def me(self):
251
"""
252
Get detailed profile information about the current user.
253
254
Returns:
255
dict: Current user profile object with private information
256
"""
257
258
def current_user(self):
259
"""
260
Alias for me(). Get current user profile.
261
262
Returns:
263
dict: Current user profile object
264
"""
265
```
266
267
### Pagination Utilities
268
269
Navigate through paginated results from API responses.
270
271
```python { .api }
272
def next(self, result):
273
"""
274
Get next page of results.
275
276
Args:
277
result (dict): Previous result object with paging information
278
279
Returns:
280
dict: Next page of results, or None if no more pages
281
"""
282
283
def previous(self, result):
284
"""
285
Get previous page of results.
286
287
Args:
288
result (dict): Current result object with paging information
289
290
Returns:
291
dict: Previous page of results, or None if at first page
292
"""
293
```
294
295
### Market Information
296
297
Access available markets and country codes.
298
299
```python { .api }
300
def available_markets(self):
301
"""
302
Get list of markets where Spotify is available.
303
304
Returns:
305
dict: Object containing list of available market codes
306
"""
307
```
308
309
## Usage Examples
310
311
### Basic Search and Track Information
312
313
```python
314
import spotipy
315
from spotipy.oauth2 import SpotifyClientCredentials
316
317
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
318
319
# Search for tracks
320
results = sp.search(q='artist:radiohead track:creep', type='track', limit=1)
321
track = results['tracks']['items'][0]
322
323
# Get detailed track information
324
track_details = sp.track(track['id'])
325
print(f"Track: {track_details['name']}")
326
print(f"Album: {track_details['album']['name']}")
327
print(f"Artists: {', '.join([artist['name'] for artist in track_details['artists']])}")
328
329
# Get audio features
330
features = sp.audio_features([track['id']])[0]
331
print(f"Danceability: {features['danceability']}")
332
print(f"Energy: {features['energy']}")
333
print(f"Valence: {features['valence']}")
334
```
335
336
### Artist Exploration
337
338
```python
339
# Search for artist
340
results = sp.search(q='radiohead', type='artist', limit=1)
341
artist = results['artists']['items'][0]
342
343
# Get artist's albums
344
albums = sp.artist_albums(artist['id'], album_type='album', limit=10)
345
print(f"Albums by {artist['name']}:")
346
for album in albums['items']:
347
print(f" {album['name']} ({album['release_date'][:4]})")
348
349
# Get top tracks
350
top_tracks = sp.artist_top_tracks(artist['id'], country='US')
351
print(f"\\nTop tracks:")
352
for track in top_tracks['tracks'][:5]:
353
print(f" {track['name']}")
354
355
# Find related artists
356
related = sp.artist_related_artists(artist['id'])
357
print(f"\\nRelated artists:")
358
for artist in related['artists'][:5]:
359
print(f" {artist['name']}")
360
```
361
362
### Multi-Market Search
363
364
```python
365
# Search across multiple markets
366
markets = ['US', 'GB', 'CA', 'AU']
367
results = sp.search_markets(
368
q='taylor swift',
369
type='album',
370
markets=markets,
371
limit=5,
372
total=20
373
)
374
375
for market, market_results in results.items():
376
print(f"Results for {market}:")
377
for album in market_results['albums']['items']:
378
print(f" {album['name']} - Available: {market in album['available_markets']}")
379
```
380
381
## Error Handling
382
383
The client automatically handles rate limiting with exponential backoff and retry logic. Authentication errors, network issues, and API errors are raised as appropriate exceptions:
384
385
```python
386
from spotipy.exceptions import SpotifyException
387
388
try:
389
track = sp.track('invalid_track_id')
390
except SpotifyException as e:
391
print(f"Spotify API Error: {e.http_status} - {e.msg}")
392
if e.http_status == 429: # Rate limited
393
retry_after = e.headers.get('Retry-After', 1)
394
print(f"Rate limited. Retry after {retry_after} seconds")
395
```