0
# Browse and Discover
1
2
Spotify's discovery and browse features including featured playlists, new releases, categories, personalized recommendations, and audio analysis capabilities. These endpoints provide access to Spotify's curated content and recommendation engine.
3
4
## Capabilities
5
6
### Featured Content
7
8
Access Spotify's editorially curated featured playlists and new releases.
9
10
```python { .api }
11
def featured_playlists(self, country=None, locale=None, timestamp=None, limit=20, offset=0):
12
"""
13
Get featured playlists.
14
15
Args:
16
country (str, optional): ISO 3166-1 alpha-2 country code
17
locale (str, optional): Desired language for results (ISO 639-1 language code and ISO 3166-1 alpha-2 country code)
18
timestamp (str, optional): ISO 8601 timestamp for when to retrieve featured playlists
19
limit (int): Number of playlists to return (1-50, default: 20)
20
offset (int): Index of first playlist (default: 0)
21
22
Returns:
23
dict: Object with message and paging object of featured playlists
24
"""
25
26
def new_releases(self, country=None, limit=20, offset=0):
27
"""
28
Get new album releases.
29
30
Args:
31
country (str, optional): ISO 3166-1 alpha-2 country code
32
limit (int): Number of albums to return (1-50, default: 20)
33
offset (int): Index of first album (default: 0)
34
35
Returns:
36
dict: Paging object of new album releases
37
"""
38
```
39
40
### Categories
41
42
Browse Spotify's genre and mood categories with associated playlists.
43
44
```python { .api }
45
def categories(self, country=None, locale=None, limit=20, offset=0):
46
"""
47
Get list of categories.
48
49
Args:
50
country (str, optional): ISO 3166-1 alpha-2 country code
51
locale (str, optional): Desired language for results
52
limit (int): Number of categories to return (1-50, default: 20)
53
offset (int): Index of first category (default: 0)
54
55
Returns:
56
dict: Paging object of category objects
57
"""
58
59
def category(self, category_id, country=None, locale=None):
60
"""
61
Get single category.
62
63
Args:
64
category_id (str): Spotify category ID
65
country (str, optional): ISO 3166-1 alpha-2 country code
66
locale (str, optional): Desired language for results
67
68
Returns:
69
dict: Category object with id, name, href, icons
70
"""
71
72
def category_playlists(self, category_id, country=None, limit=20, offset=0):
73
"""
74
Get playlists for a category.
75
76
Args:
77
category_id (str): Spotify category ID
78
country (str, optional): ISO 3166-1 alpha-2 country code
79
limit (int): Number of playlists to return (1-50, default: 20)
80
offset (int): Index of first playlist (default: 0)
81
82
Returns:
83
dict: Paging object of playlists for the category
84
"""
85
```
86
87
### Recommendations
88
89
Get personalized track recommendations based on seed tracks, artists, and genres with fine-tuned audio features.
90
91
```python { .api }
92
def recommendations(self, seed_artists=None, seed_genres=None, seed_tracks=None,
93
limit=20, country=None, **kwargs):
94
"""
95
Get track recommendations.
96
97
Args:
98
seed_artists (list, optional): List of artist IDs for seed (max 5 total seeds)
99
seed_genres (list, optional): List of genre names for seed (max 5 total seeds)
100
seed_tracks (list, optional): List of track IDs for seed (max 5 total seeds)
101
limit (int): Number of recommendations to return (1-100, default: 20)
102
country (str, optional): ISO 3166-1 alpha-2 country code
103
**kwargs: Audio feature targets and ranges (min_*, max_*, target_*)
104
105
Audio Feature Parameters:
106
- acousticness: 0.0-1.0
107
- danceability: 0.0-1.0
108
- duration_ms: milliseconds
109
- energy: 0.0-1.0
110
- instrumentalness: 0.0-1.0
111
- key: 0-11 (C, C#, D, etc.)
112
- liveness: 0.0-1.0
113
- loudness: -60.0 to 0.0 dB
114
- mode: 0 (minor) or 1 (major)
115
- popularity: 0-100
116
- speechiness: 0.0-1.0
117
- tempo: BPM
118
- time_signature: 3-7
119
- valence: 0.0-1.0 (positivity)
120
121
Returns:
122
dict: Recommendations object with tracks array and seed info
123
"""
124
125
def recommendation_genre_seeds(self):
126
"""
127
Get available genre seeds for recommendations.
128
129
Returns:
130
dict: Object containing list of available genre strings
131
"""
132
```
133
134
### Audio Analysis
135
136
Detailed audio analysis and features for tracks.
137
138
```python { .api }
139
def audio_features(self, tracks=[]):
140
"""
141
Get audio features for tracks.
142
143
Args:
144
tracks (list): List of track IDs or URIs (max 100)
145
146
Returns:
147
dict: Audio features objects with acousticness, danceability, energy, etc.
148
"""
149
150
def audio_analysis(self, track_id):
151
"""
152
Get detailed audio analysis for a track.
153
154
Args:
155
track_id (str): Spotify track ID or URI
156
157
Returns:
158
dict: Detailed audio analysis with bars, beats, sections, segments, tatums, meta, track
159
"""
160
```
161
162
## Usage Examples
163
164
### Discovering Featured Content
165
166
```python
167
import spotipy
168
from spotipy.oauth2 import SpotifyClientCredentials
169
170
sp = spotipy.Spotify(client_credentials_manager=SpotifyClientCredentials())
171
172
# Get featured playlists for US market
173
featured = sp.featured_playlists(country='US', limit=10)
174
print(f"Featured message: {featured['message']}")
175
print("\\nFeatured playlists:")
176
177
for playlist in featured['playlists']['items']:
178
print(f" π {playlist['name']} by {playlist['owner']['display_name']}")
179
print(f" {playlist['tracks']['total']} tracks, {playlist['followers']['total']} followers")
180
print(f" {playlist['description']}")
181
182
# Get new releases
183
new_releases = sp.new_releases(country='US', limit=10)
184
print("\\nπ New album releases:")
185
186
for album in new_releases['albums']['items']:
187
artist_names = ', '.join([artist['name'] for artist in album['artists']])
188
print(f" πΏ {album['name']} - {artist_names}")
189
print(f" Released: {album['release_date']} | Type: {album['album_type']}")
190
if album['total_tracks'] > 1:
191
print(f" {album['total_tracks']} tracks")
192
```
193
194
### Exploring Categories
195
196
```python
197
# Get all categories
198
categories = sp.categories(country='US', limit=50)
199
print("π Available categories:")
200
201
category_list = categories['categories']['items']
202
for category in category_list[:10]: # Show first 10
203
print(f" {category['name']} (ID: {category['id']})")
204
205
# Explore specific category
206
pop_category = sp.category('pop', country='US')
207
print(f"\\nπ Category: {pop_category['name']}")
208
209
# Get playlists for pop category
210
pop_playlists = sp.category_playlists('pop', country='US', limit=20)
211
print(f"\\nTop pop playlists:")
212
213
for playlist in pop_playlists['playlists']['items']:
214
print(f" π΅ {playlist['name']}")
215
print(f" {playlist['tracks']['total']} tracks, {playlist['followers']['total']} followers")
216
```
217
218
### Personalized Recommendations
219
220
```python
221
# Get available genres
222
genres = sp.recommendation_genre_seeds()
223
print(f"Available genres: {', '.join(genres['genres'][:10])}...") # Show first 10
224
225
# Get recommendations based on favorite artists and genres
226
recommendations = sp.recommendations(
227
seed_artists=['4Z8W4fKeB5YxbusRsdQVPb'], # Radiohead
228
seed_genres=['alternative', 'indie'],
229
seed_tracks=['4iV5W9uYEdYUVa79Axb7Rh'], # Mr. Brightside
230
limit=20,
231
country='US'
232
)
233
234
print("\\nπ― Personalized recommendations:")
235
for track in recommendations['tracks']:
236
artist_names = ', '.join([artist['name'] for artist in track['artists']])
237
print(f" π΅ {track['name']} - {artist_names}")
238
print(f" Popularity: {track['popularity']}/100")
239
240
# Show seed information
241
print("\\nπ± Based on seeds:")
242
for seed in recommendations['seeds']:
243
print(f" {seed['type']}: {seed.get('id', 'N/A')} (after filtering: {seed['afterFilteringSize']})")
244
```
245
246
### Advanced Recommendations with Audio Features
247
248
```python
249
# Get upbeat, danceable recommendations
250
upbeat_recs = sp.recommendations(
251
seed_genres=['pop', 'dance'],
252
limit=15,
253
target_danceability=0.8, # High danceability
254
target_energy=0.7, # High energy
255
target_valence=0.8, # Positive mood
256
min_tempo=120, # At least 120 BPM
257
max_tempo=140, # Max 140 BPM
258
target_popularity=70 # Reasonably popular
259
)
260
261
print("πΊ Upbeat, danceable recommendations:")
262
for track in upbeat_recs['tracks']:
263
artist_names = ', '.join([artist['name'] for artist in track['artists']])
264
print(f" π {track['name']} - {artist_names}")
265
266
# Get chill, acoustic recommendations
267
chill_recs = sp.recommendations(
268
seed_genres=['acoustic', 'chill'],
269
limit=10,
270
target_acousticness=0.8, # Highly acoustic
271
target_energy=0.3, # Low energy
272
target_valence=0.6, # Moderately positive
273
max_loudness=-10, # Not too loud
274
target_instrumentalness=0.1 # Some vocals
275
)
276
277
print("\\nπ Chill, acoustic recommendations:")
278
for track in chill_recs['tracks']:
279
artist_names = ', '.join([artist['name'] for artist in track['artists']])
280
print(f" πΈ {track['name']} - {artist_names}")
281
```
282
283
### Audio Features Analysis
284
285
```python
286
# Analyze audio features of popular tracks
287
track_ids = [
288
'4iV5W9uYEdYUVa79Axb7Rh', # Mr. Brightside
289
'0VjIjW4GlUAOLklx2J', # Bohemian Rhapsody
290
'1301WleyT98MSxVHPZCA6M' # Sweet Child O' Mine
291
]
292
293
# Get basic track info
294
tracks_info = sp.tracks(track_ids)
295
features = sp.audio_features(track_ids)
296
297
print("π΅ Audio Features Analysis:")
298
for track_info, feature in zip(tracks_info['tracks'], features):
299
if feature: # Check if features available
300
print(f"\\nπ§ {track_info['name']} - {track_info['artists'][0]['name']}")
301
print(f" Key: {feature['key']} | Mode: {'Major' if feature['mode'] else 'Minor'}")
302
print(f" Tempo: {feature['tempo']:.1f} BPM | Time Signature: {feature['time_signature']}/4")
303
print(f" Energy: {feature['energy']:.2f} | Danceability: {feature['danceability']:.2f}")
304
print(f" Valence: {feature['valence']:.2f} | Acousticness: {feature['acousticness']:.2f}")
305
print(f" Loudness: {feature['loudness']:.1f} dB | Duration: {feature['duration_ms']/1000:.1f}s")
306
```
307
308
### Detailed Audio Analysis
309
310
```python
311
# Get detailed analysis for a track
312
track_id = '4iV5W9uYEdYUVa79Axb7Rh' # Mr. Brightside
313
analysis = sp.audio_analysis(track_id)
314
315
print("π¬ Detailed Audio Analysis:")
316
print(f"Duration: {analysis['track']['duration']:.1f}s")
317
print(f"Key: {analysis['track']['key']} | Mode: {analysis['track']['mode']}")
318
print(f"Time Signature: {analysis['track']['time_signature']}")
319
print(f"Tempo: {analysis['track']['tempo']:.1f} BPM")
320
321
# Analyze sections
322
print(f"\\nπ Song Structure:")
323
print(f"Bars: {len(analysis['bars'])}")
324
print(f"Beats: {len(analysis['beats'])}")
325
print(f"Sections: {len(analysis['sections'])}")
326
print(f"Segments: {len(analysis['segments'])}")
327
328
# Show first few sections
329
print("\\nπΌ Sections breakdown:")
330
for i, section in enumerate(analysis['sections'][:5]):
331
start_time = section['start']
332
duration = section['duration']
333
confidence = section['confidence']
334
loudness = section['loudness']
335
tempo = section['tempo']
336
key = section['key']
337
338
print(f" Section {i+1}: {start_time:.1f}s-{start_time+duration:.1f}s")
339
print(f" Tempo: {tempo:.1f} BPM | Key: {key} | Loudness: {loudness:.1f} dB")
340
print(f" Confidence: {confidence:.2f}")
341
```
342
343
### Discovery Workflow
344
345
```python
346
def discover_music_by_mood(mood="happy", limit=15):
347
"""Discover music based on mood using audio features."""
348
349
mood_profiles = {
350
"happy": {
351
"seed_genres": ["pop", "dance", "funk"],
352
"target_valence": 0.8,
353
"target_energy": 0.7,
354
"target_danceability": 0.7,
355
"min_tempo": 110
356
},
357
"sad": {
358
"seed_genres": ["indie", "alternative", "singer-songwriter"],
359
"target_valence": 0.3,
360
"target_energy": 0.4,
361
"target_acousticness": 0.6,
362
"max_tempo": 100
363
},
364
"chill": {
365
"seed_genres": ["chill", "ambient", "lo-fi"],
366
"target_energy": 0.3,
367
"target_acousticness": 0.7,
368
"target_instrumentalness": 0.5,
369
"max_loudness": -15
370
},
371
"workout": {
372
"seed_genres": ["electro", "hip-hop", "rock"],
373
"target_energy": 0.9,
374
"target_danceability": 0.8,
375
"min_tempo": 130,
376
"max_tempo": 160
377
}
378
}
379
380
if mood not in mood_profiles:
381
print(f"Mood '{mood}' not available. Try: {', '.join(mood_profiles.keys())}")
382
return
383
384
profile = mood_profiles[mood]
385
recommendations = sp.recommendations(limit=limit, **profile)
386
387
print(f"π {mood.title()} Music Recommendations:")
388
for track in recommendations['tracks']:
389
artist_names = ', '.join([artist['name'] for artist in track['artists']])
390
print(f" π΅ {track['name']} - {artist_names}")
391
print(f" Album: {track['album']['name']} | Popularity: {track['popularity']}/100")
392
393
# Discover music for different moods
394
discover_music_by_mood("happy", 10)
395
print()
396
discover_music_by_mood("chill", 8)
397
```
398
399
### Market-Specific Discovery
400
401
```python
402
def explore_market(country_code, limit=5):
403
"""Explore what's popular in a specific market."""
404
405
print(f"π Exploring {country_code} market:")
406
407
# Featured playlists
408
try:
409
featured = sp.featured_playlists(country=country_code, limit=limit)
410
print(f"\\nπ Featured Playlists:")
411
for playlist in featured['playlists']['items']:
412
print(f" {playlist['name']} ({playlist['tracks']['total']} tracks)")
413
except Exception as e:
414
print(f" Featured playlists not available: {e}")
415
416
# New releases
417
try:
418
releases = sp.new_releases(country=country_code, limit=limit)
419
print(f"\\nπΏ New Releases:")
420
for album in releases['albums']['items']:
421
artist_names = ', '.join([artist['name'] for artist in album['artists']])
422
print(f" {album['name']} - {artist_names}")
423
except Exception as e:
424
print(f" New releases not available: {e}")
425
426
# Categories
427
try:
428
categories = sp.categories(country=country_code, limit=limit)
429
print(f"\\nπ Popular Categories:")
430
for category in categories['categories']['items']:
431
print(f" {category['name']}")
432
except Exception as e:
433
print(f" Categories not available: {e}")
434
435
# Explore different markets
436
markets = ['US', 'GB', 'DE', 'JP', 'BR']
437
for market in markets:
438
explore_market(market, 3)
439
print("-" * 50)
440
```
441
442
## Audio Feature Ranges
443
444
When using recommendations with audio feature parameters:
445
446
- **acousticness**: 0.0 (not acoustic) to 1.0 (very acoustic)
447
- **danceability**: 0.0 (not danceable) to 1.0 (very danceable)
448
- **energy**: 0.0 (low energy) to 1.0 (high energy)
449
- **instrumentalness**: 0.0 (vocals) to 1.0 (instrumental)
450
- **liveness**: 0.0 (studio) to 1.0 (live performance)
451
- **loudness**: -60.0 to 0.0 dB (typical range: -60 to 0)
452
- **speechiness**: 0.0 (not speech-like) to 1.0 (very speech-like)
453
- **valence**: 0.0 (negative mood) to 1.0 (positive mood)
454
- **tempo**: BPM (typical range: 50-200)
455
- **popularity**: 0 (least popular) to 100 (most popular)
456
- **key**: 0 (C) to 11 (B) in chromatic order
457
- **mode**: 0 (minor) or 1 (major)
458
- **time_signature**: 3 to 7 (beats per bar)
459
460
Use `min_*`, `max_*`, and `target_*` prefixes with these feature names for recommendation fine-tuning.