0
# User Library and Profile
1
2
Manage the authenticated user's personal library including saved tracks, albums, shows, episodes, followed artists, and profile information. All operations require appropriate OAuth scopes.
3
4
## Capabilities
5
6
### User Profile Information
7
8
Access current user's profile data and public user information.
9
10
```python { .api }
11
def me(self):
12
"""
13
Get detailed profile information about the current user.
14
15
Requires scope: user-read-private, user-read-email
16
17
Returns:
18
dict: User profile with id, display_name, email, followers, images, etc.
19
"""
20
21
def current_user(self):
22
"""
23
Alias for me(). Get current user profile.
24
25
Returns:
26
dict: Current user profile object
27
"""
28
29
def user(self, user):
30
"""
31
Get public profile information about any Spotify user.
32
33
Args:
34
user (str): Spotify user ID
35
36
Returns:
37
dict: Public user profile with id, display_name, followers, images
38
"""
39
```
40
41
### Saved Tracks
42
43
Manage the user's saved tracks library.
44
45
```python { .api }
46
def current_user_saved_tracks(self, limit=20, offset=0, market=None):
47
"""
48
Get user's saved tracks.
49
50
Requires scope: user-library-read
51
52
Args:
53
limit (int): Number of tracks to return (1-50, default: 20)
54
offset (int): Index of first track (default: 0)
55
market (str, optional): ISO 3166-1 alpha-2 country code
56
57
Returns:
58
dict: Paging object of saved track objects with added_at timestamps
59
"""
60
61
def current_user_saved_tracks_add(self, tracks=None):
62
"""
63
Save tracks to user's library.
64
65
Requires scope: user-library-modify
66
67
Args:
68
tracks (list): List of track IDs or URIs (max 50)
69
70
Returns:
71
None
72
"""
73
74
def current_user_saved_tracks_delete(self, tracks=None):
75
"""
76
Remove tracks from user's library.
77
78
Requires scope: user-library-modify
79
80
Args:
81
tracks (list): List of track IDs or URIs (max 50)
82
83
Returns:
84
None
85
"""
86
87
def current_user_saved_tracks_contains(self, tracks=None):
88
"""
89
Check if tracks are saved in user's library.
90
91
Requires scope: user-library-read
92
93
Args:
94
tracks (list): List of track IDs or URIs (max 50)
95
96
Returns:
97
list: Boolean list indicating which tracks are saved
98
"""
99
```
100
101
### Saved Albums
102
103
Manage the user's saved albums library.
104
105
```python { .api }
106
def current_user_saved_albums(self, limit=20, offset=0, market=None):
107
"""
108
Get user's saved albums.
109
110
Requires scope: user-library-read
111
112
Args:
113
limit (int): Number of albums to return (1-50, default: 20)
114
offset (int): Index of first album (default: 0)
115
market (str, optional): ISO 3166-1 alpha-2 country code
116
117
Returns:
118
dict: Paging object of saved album objects with added_at timestamps
119
"""
120
121
def current_user_saved_albums_add(self, albums=[]):
122
"""
123
Save albums to user's library.
124
125
Requires scope: user-library-modify
126
127
Args:
128
albums (list): List of album IDs or URIs (max 50)
129
130
Returns:
131
None
132
"""
133
134
def current_user_saved_albums_delete(self, albums=[]):
135
"""
136
Remove albums from user's library.
137
138
Requires scope: user-library-modify
139
140
Args:
141
albums (list): List of album IDs or URIs (max 50)
142
143
Returns:
144
None
145
"""
146
147
def current_user_saved_albums_contains(self, albums=[]):
148
"""
149
Check if albums are saved in user's library.
150
151
Requires scope: user-library-read
152
153
Args:
154
albums (list): List of album IDs or URIs (max 50)
155
156
Returns:
157
list: Boolean list indicating which albums are saved
158
"""
159
```
160
161
### Saved Episodes
162
163
Manage the user's saved podcast episodes.
164
165
```python { .api }
166
def current_user_saved_episodes(self, limit=20, offset=0, market=None):
167
"""
168
Get user's saved episodes.
169
170
Requires scope: user-library-read
171
172
Args:
173
limit (int): Number of episodes to return (1-50, default: 20)
174
offset (int): Index of first episode (default: 0)
175
market (str, optional): ISO 3166-1 alpha-2 country code
176
177
Returns:
178
dict: Paging object of saved episode objects with added_at timestamps
179
"""
180
181
def current_user_saved_episodes_add(self, episodes=None):
182
"""
183
Save episodes to user's library.
184
185
Requires scope: user-library-modify
186
187
Args:
188
episodes (list): List of episode IDs or URIs (max 50)
189
190
Returns:
191
None
192
"""
193
194
def current_user_saved_episodes_delete(self, episodes=None):
195
"""
196
Remove episodes from user's library.
197
198
Requires scope: user-library-modify
199
200
Args:
201
episodes (list): List of episode IDs or URIs (max 50)
202
203
Returns:
204
None
205
"""
206
207
def current_user_saved_episodes_contains(self, episodes=None):
208
"""
209
Check if episodes are saved in user's library.
210
211
Requires scope: user-library-read
212
213
Args:
214
episodes (list): List of episode IDs or URIs (max 50)
215
216
Returns:
217
list: Boolean list indicating which episodes are saved
218
"""
219
```
220
221
### Saved Shows
222
223
Manage the user's saved podcast shows.
224
225
```python { .api }
226
def current_user_saved_shows(self, limit=20, offset=0, market=None):
227
"""
228
Get user's saved shows.
229
230
Requires scope: user-library-read
231
232
Args:
233
limit (int): Number of shows to return (1-50, default: 20)
234
offset (int): Index of first show (default: 0)
235
market (str, optional): ISO 3166-1 alpha-2 country code
236
237
Returns:
238
dict: Paging object of saved show objects with added_at timestamps
239
"""
240
241
def current_user_saved_shows_add(self, shows=[]):
242
"""
243
Save shows to user's library.
244
245
Requires scope: user-library-modify
246
247
Args:
248
shows (list): List of show IDs or URIs (max 50)
249
250
Returns:
251
None
252
"""
253
254
def current_user_saved_shows_delete(self, shows=[]):
255
"""
256
Remove shows from user's library.
257
258
Requires scope: user-library-modify
259
260
Args:
261
shows (list): List of show IDs or URIs (max 50)
262
263
Returns:
264
None
265
"""
266
267
def current_user_saved_shows_contains(self, shows=[]):
268
"""
269
Check if shows are saved in user's library.
270
271
Requires scope: user-library-read
272
273
Args:
274
shows (list): List of show IDs or URIs (max 50)
275
276
Returns:
277
list: Boolean list indicating which shows are saved
278
"""
279
```
280
281
### Following Artists and Users
282
283
Manage following relationships with artists and other users.
284
285
```python { .api }
286
def current_user_followed_artists(self, limit=20, after=None):
287
"""
288
Get artists followed by the current user.
289
290
Requires scope: user-follow-read
291
292
Args:
293
limit (int): Number of artists to return (1-50, default: 20)
294
after (str, optional): Artist ID for pagination cursor
295
296
Returns:
297
dict: Cursor-based paging object of artist objects
298
"""
299
300
def current_user_following_artists(self, ids=None):
301
"""
302
Check if current user follows specific artists.
303
304
Requires scope: user-follow-read
305
306
Args:
307
ids (list): List of artist IDs (max 50)
308
309
Returns:
310
list: Boolean list indicating which artists are followed
311
"""
312
313
def current_user_following_users(self, ids=None):
314
"""
315
Check if current user follows specific users.
316
317
Requires scope: user-follow-read
318
319
Args:
320
ids (list): List of user IDs (max 50)
321
322
Returns:
323
list: Boolean list indicating which users are followed
324
"""
325
326
def user_follow_artists(self, ids=[]):
327
"""
328
Follow artists.
329
330
Requires scope: user-follow-modify
331
332
Args:
333
ids (list): List of artist IDs to follow (max 50)
334
335
Returns:
336
None
337
"""
338
339
def user_follow_users(self, ids=[]):
340
"""
341
Follow users.
342
343
Requires scope: user-follow-modify
344
345
Args:
346
ids (list): List of user IDs to follow (max 50)
347
348
Returns:
349
None
350
"""
351
352
def user_unfollow_artists(self, ids=[]):
353
"""
354
Unfollow artists.
355
356
Requires scope: user-follow-modify
357
358
Args:
359
ids (list): List of artist IDs to unfollow (max 50)
360
361
Returns:
362
None
363
"""
364
365
def user_unfollow_users(self, ids=[]):
366
"""
367
Unfollow users.
368
369
Requires scope: user-follow-modify
370
371
Args:
372
ids (list): List of user IDs to unfollow (max 50)
373
374
Returns:
375
None
376
"""
377
```
378
379
### Top Content
380
381
Access user's top artists and tracks based on listening history.
382
383
```python { .api }
384
def current_user_top_artists(self, limit=20, offset=0, time_range="medium_term"):
385
"""
386
Get user's top artists.
387
388
Requires scope: user-top-read
389
390
Args:
391
limit (int): Number of artists to return (1-50, default: 20)
392
offset (int): Index of first result (default: 0)
393
time_range (str): Time period - 'short_term' (4 weeks), 'medium_term' (6 months), 'long_term' (years)
394
395
Returns:
396
dict: Paging object of artist objects
397
"""
398
399
def current_user_top_tracks(self, limit=20, offset=0, time_range="medium_term"):
400
"""
401
Get user's top tracks.
402
403
Requires scope: user-top-read
404
405
Args:
406
limit (int): Number of tracks to return (1-50, default: 20)
407
offset (int): Index of first result (default: 0)
408
time_range (str): Time period - 'short_term' (4 weeks), 'medium_term' (6 months), 'long_term' (years)
409
410
Returns:
411
dict: Paging object of track objects
412
"""
413
```
414
415
### Recently Played
416
417
Access user's recently played tracks with timestamp information.
418
419
```python { .api }
420
def current_user_recently_played(self, limit=50, after=None, before=None):
421
"""
422
Get user's recently played tracks.
423
424
Requires scope: user-read-recently-played
425
426
Args:
427
limit (int): Number of items to return (1-50, default: 50)
428
after (int, optional): Unix timestamp in milliseconds - returns tracks played after this time
429
before (int, optional): Unix timestamp in milliseconds - returns tracks played before this time
430
431
Returns:
432
dict: Cursor-based paging object of played track objects with context and played_at timestamp
433
"""
434
```
435
436
## Usage Examples
437
438
### Managing Saved Tracks
439
440
```python
441
import spotipy
442
from spotipy.oauth2 import SpotifyOAuth
443
444
scope = "user-library-read user-library-modify"
445
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
446
447
# Get saved tracks
448
saved_tracks = sp.current_user_saved_tracks(limit=50)
449
print(f"You have {saved_tracks['total']} saved tracks")
450
451
for item in saved_tracks['items']:
452
track = item['track']
453
added_at = item['added_at']
454
print(f"Added {added_at[:10]}: {track['name']} by {track['artists'][0]['name']}")
455
456
# Save new tracks
457
track_ids = ['4iV5W9uYEdYUVa79Axb7Rh', '1301WleyT98MSxVHPZCA6M'] # Example track IDs
458
sp.current_user_saved_tracks_add(tracks=track_ids)
459
print("Tracks saved to library!")
460
461
# Check if specific tracks are saved
462
saved_status = sp.current_user_saved_tracks_contains(tracks=track_ids)
463
for track_id, is_saved in zip(track_ids, saved_status):
464
print(f"Track {track_id}: {'Saved' if is_saved else 'Not saved'}")
465
```
466
467
### Following Artists
468
469
```python
470
scope = "user-follow-read user-follow-modify"
471
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
472
473
# Get followed artists
474
followed = sp.current_user_followed_artists(limit=20)
475
print(f"Following {followed['artists']['total']} artists:")
476
477
for artist in followed['artists']['items']:
478
print(f" {artist['name']} ({artist['followers']['total']} followers)")
479
480
# Follow new artists
481
artist_ids = ['4Z8W4fKeB5YxbusRsdQVPb'] # Radiohead
482
sp.user_follow_artists(ids=artist_ids)
483
print("Now following Radiohead!")
484
485
# Check following status
486
following_status = sp.current_user_following_artists(ids=artist_ids)
487
print(f"Following Radiohead: {following_status[0]}")
488
```
489
490
### User's Top Content
491
492
```python
493
scope = "user-top-read"
494
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
495
496
# Get top artists for different time ranges
497
time_ranges = ['short_term', 'medium_term', 'long_term']
498
time_labels = ['Last 4 weeks', 'Last 6 months', 'All time']
499
500
for time_range, label in zip(time_ranges, time_labels):
501
print(f"\\nTop artists - {label}:")
502
top_artists = sp.current_user_top_artists(limit=5, time_range=time_range)
503
504
for i, artist in enumerate(top_artists['items'], 1):
505
print(f" {i}. {artist['name']} ({', '.join(artist['genres'][:2])})")
506
507
# Get top tracks
508
print("\\nTop tracks - Last 6 months:")
509
top_tracks = sp.current_user_top_tracks(limit=10, time_range='medium_term')
510
511
for i, track in enumerate(top_tracks['items'], 1):
512
artist_names = ', '.join([artist['name'] for artist in track['artists']])
513
print(f" {i}. {track['name']} - {artist_names}")
514
```
515
516
### Recently Played Analysis
517
518
```python
519
import datetime
520
scope = "user-read-recently-played"
521
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
522
523
# Get recently played tracks
524
recently_played = sp.current_user_recently_played(limit=50)
525
526
print("Recently played tracks:")
527
artist_counts = {}
528
529
for item in recently_played['items']:
530
track = item['track']
531
played_at = item['played_at']
532
context = item.get('context', {})
533
534
# Parse timestamp
535
played_time = datetime.datetime.fromisoformat(played_at.replace('Z', '+00:00'))
536
537
# Count artists
538
artist_name = track['artists'][0]['name']
539
artist_counts[artist_name] = artist_counts.get(artist_name, 0) + 1
540
541
# Show context if available
542
context_info = ""
543
if context and context['type'] == 'playlist':
544
context_info = f" (from playlist)"
545
elif context and context['type'] == 'album':
546
context_info = f" (from album)"
547
548
print(f" {played_time.strftime('%m/%d %H:%M')}: {track['name']} - {artist_name}{context_info}")
549
550
# Show most played artists
551
print("\\nMost played artists in recent history:")
552
for artist, count in sorted(artist_counts.items(), key=lambda x: x[1], reverse=True)[:5]:
553
print(f" {artist}: {count} plays")
554
```
555
556
### User Profile Information
557
558
```python
559
scope = "user-read-private user-read-email"
560
sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=scope))
561
562
# Get current user profile
563
user = sp.me()
564
565
print(f"User Profile:")
566
print(f" Display Name: {user.get('display_name', 'Not set')}")
567
print(f" Email: {user.get('email', 'Not available')}")
568
print(f" Country: {user.get('country', 'Not available')}")
569
print(f" Followers: {user['followers']['total']}")
570
print(f" Subscription: {user.get('product', 'Not available')}")
571
572
if user.get('images'):
573
print(f" Profile Image: {user['images'][0]['url']}")
574
575
# Compare with another user's public profile
576
public_user = sp.user('spotify') # Spotify's official account
577
print(f"\\nSpotify Official Account:")
578
print(f" Display Name: {public_user['display_name']}")
579
print(f" Followers: {public_user['followers']['total']}")
580
```
581
582
## Required Scopes Summary
583
584
- **user-read-private**: Access private user profile information
585
- **user-read-email**: Access user's email address
586
- **user-library-read**: Read user's saved content
587
- **user-library-modify**: Modify user's saved content
588
- **user-follow-read**: Read user's followed artists and users
589
- **user-follow-modify**: Modify user's followed artists and users
590
- **user-top-read**: Read user's top artists and tracks
591
- **user-read-recently-played**: Read user's recently played tracks