0
# Server Connection & Management
1
2
Core functionality for connecting to Plex Media Servers, managing server settings, accessing server information, and performing administrative tasks.
3
4
## Capabilities
5
6
### PlexServer Connection
7
8
Primary class for connecting to and interacting with a Plex Media Server.
9
10
```python { .api }
11
class PlexServer:
12
def __init__(self, baseurl=None, token=None, session=None, timeout=None):
13
"""
14
Connect to a Plex Media Server.
15
16
Args:
17
baseurl (str): Server URL (e.g., 'http://localhost:32400')
18
token (str): Authentication token
19
session (requests.Session, optional): HTTP session
20
timeout (int, optional): Request timeout in seconds
21
"""
22
23
def query(self, key, method=None, headers=None, params=None, timeout=None, **kwargs):
24
"""
25
Make raw API query to Plex server.
26
27
Args:
28
key (str): API endpoint path
29
method (str, optional): HTTP method (GET, POST, etc.)
30
headers (dict, optional): Additional HTTP headers
31
params (dict, optional): Query parameters
32
timeout (int, optional): Request timeout
33
34
Returns:
35
requests.Response: Raw HTTP response object
36
"""
37
```
38
39
### Server Properties
40
41
Access server information and core functionality.
42
43
```python { .api }
44
class PlexServer:
45
@property
46
def library(self):
47
"""Library: Access to media library sections and content."""
48
49
@property
50
def settings(self):
51
"""Settings: Server configuration and settings management."""
52
53
@property
54
def account(self):
55
"""Account: Server account information and statistics."""
56
57
@property
58
def identity(self):
59
"""Identity: Server identity and version information."""
60
```
61
62
### Content Search & Discovery
63
64
Search across all server content and access various content views.
65
66
```python { .api }
67
class PlexServer:
68
def search(self, query, mediatype=None, limit=None, sectionId=None):
69
"""
70
Search across all server content.
71
72
Args:
73
query (str): Search query string
74
mediatype (str, optional): Filter by media type ('movie', 'show', 'artist', etc.)
75
limit (int, optional): Maximum number of results
76
sectionId (int, optional): Search within specific library section
77
78
Returns:
79
list: List of matching media objects
80
"""
81
82
def sessions(self):
83
"""
84
Get active playback sessions.
85
86
Returns:
87
list: List of active session objects
88
"""
89
90
def history(self):
91
"""
92
Get server playback history.
93
94
Returns:
95
list: List of historical playback records
96
"""
97
98
def activities(self):
99
"""
100
Get background server activities.
101
102
Returns:
103
list: List of Activity objects representing background tasks
104
"""
105
```
106
107
### Client Management
108
109
Access and control connected Plex clients.
110
111
```python { .api }
112
class PlexServer:
113
def clients(self):
114
"""
115
Get all connected Plex clients.
116
117
Returns:
118
list: List of PlexClient objects
119
"""
120
121
def client(self, name):
122
"""
123
Get specific client by name.
124
125
Args:
126
name (str): Client name to find
127
128
Returns:
129
PlexClient: Client object for the specified name
130
131
Raises:
132
NotFound: If client with specified name is not found
133
"""
134
```
135
136
### Playlist & Collection Management
137
138
Create and manage server-level playlists and collections.
139
140
```python { .api }
141
class PlexServer:
142
def playlists(self):
143
"""
144
Get all server playlists.
145
146
Returns:
147
list: List of Playlist objects
148
"""
149
150
def createPlaylist(self, title, section=None, items=None, smart=False, limit=None, libtype=None, sort=None, filters=None, m3ufilepath=None, **kwargs):
151
"""
152
Create a new playlist.
153
154
Args:
155
title (str): Playlist title
156
section (LibrarySection, optional): Library section for smart playlists
157
items (list, optional): Initial items for regular playlists
158
smart (bool): Create smart playlist vs regular playlist
159
limit (int, optional): Limit number of items for smart playlists
160
libtype (str, optional): Media type for smart playlists ('movie', 'show', 'artist')
161
sort (str, optional): Sort order for smart playlists
162
filters (dict, optional): Filter criteria for smart playlists
163
m3ufilepath (str, optional): Path to M3U file to import
164
**kwargs: Additional playlist properties
165
166
Returns:
167
Playlist: Created playlist object
168
"""
169
170
def createCollection(self, title, section, items=None, smart=False, **kwargs):
171
"""
172
Create a new collection.
173
174
Args:
175
title (str): Collection title
176
section (LibrarySection): Target library section
177
items (list, optional): Initial collection items
178
smart (bool): Create smart collection vs regular collection
179
**kwargs: Additional collection properties
180
181
Returns:
182
Collection: Created collection object
183
"""
184
185
def createPlayQueue(self, item, **kwargs):
186
"""
187
Create a playback queue.
188
189
Args:
190
item: Media item to start queue with
191
**kwargs: Additional queue parameters
192
193
Returns:
194
PlayQueue: Created play queue object
195
"""
196
```
197
198
### User & Device Management
199
200
Manage server users, devices, and administrative access.
201
202
```python { .api }
203
class PlexServer:
204
def systemAccounts(self):
205
"""
206
Get server system accounts.
207
208
Returns:
209
list: List of system account objects
210
"""
211
212
def systemDevices(self):
213
"""
214
Get connected system devices.
215
216
Returns:
217
list: List of system device objects
218
"""
219
220
def switchUser(self, username):
221
"""
222
Switch to different user context on server.
223
224
Args:
225
username (str): Username to switch to
226
227
Returns:
228
PlexServer: Server instance with new user context
229
"""
230
231
def myPlexAccount(self):
232
"""
233
Get associated MyPlex account for this server.
234
235
Returns:
236
MyPlexAccount: Associated account object
237
"""
238
239
def claim(self, account):
240
"""
241
Claim unclaimed server with MyPlex account.
242
243
Args:
244
account (MyPlexAccount): Account to claim server with
245
"""
246
247
def unclaim(self):
248
"""Unclaim server from MyPlex account."""
249
```
250
251
### Filesystem Browsing
252
253
Browse and navigate server filesystem through Plex API.
254
255
```python { .api }
256
class PlexServer:
257
def browse(self, path='/'):
258
"""
259
Browse server filesystem at specified path.
260
261
Args:
262
path (str): Filesystem path to browse
263
264
Returns:
265
list: List of filesystem items (directories and files)
266
"""
267
268
def walk(self, path='/'):
269
"""
270
Recursively walk server filesystem starting at path.
271
272
Args:
273
path (str): Starting path for filesystem walk
274
275
Yields:
276
tuple: (dirpath, dirnames, filenames) for each directory
277
"""
278
```
279
280
### Server Maintenance
281
282
Perform server maintenance and administrative tasks.
283
284
```python { .api }
285
class PlexServer:
286
def refreshContent(self):
287
"""Refresh all server content metadata."""
288
289
def butlerTasks(self):
290
"""
291
Get available maintenance tasks.
292
293
Returns:
294
list: List of ButlerTask objects
295
"""
296
297
def runButlerTask(self, task):
298
"""
299
Execute a maintenance task.
300
301
Args:
302
task (str or ButlerTask): Task name or task object to execute
303
"""
304
```
305
306
### Server Information Classes
307
308
Access detailed server information and statistics.
309
310
```python { .api }
311
class Account:
312
"""Server account information and statistics."""
313
@property
314
def id(self): ...
315
@property
316
def title(self): ...
317
@property
318
def thumb(self): ...
319
320
class Identity:
321
"""Server identity and version information."""
322
@property
323
def machineIdentifier(self): ...
324
@property
325
def version(self): ...
326
@property
327
def platform(self): ...
328
329
class Activity:
330
"""Background server activity or task."""
331
@property
332
def title(self): ...
333
@property
334
def type(self): ...
335
@property
336
def progress(self): ...
337
338
class ButlerTask:
339
"""Server maintenance task."""
340
@property
341
def name(self): ...
342
@property
343
def title(self): ...
344
@property
345
def description(self): ...
346
```
347
348
### Server Settings Management
349
350
Configure server settings and preferences.
351
352
```python { .api }
353
class Settings:
354
"""Server settings interface."""
355
def get(self, key):
356
"""
357
Get setting value by key.
358
359
Args:
360
key (str): Setting key name
361
362
Returns:
363
Setting: Setting object with current value
364
"""
365
366
def save(self):
367
"""Save any modified settings to server."""
368
369
class Setting:
370
"""Individual server setting."""
371
@property
372
def id(self): ...
373
@property
374
def label(self): ...
375
@property
376
def value(self): ...
377
378
def setValue(self, value):
379
"""Set new value for this setting."""
380
```
381
382
## Usage Examples
383
384
### Basic Server Connection
385
386
```python
387
from plexapi.server import PlexServer
388
389
# Direct connection with token
390
plex = PlexServer('http://192.168.1.100:32400', 'your-auth-token')
391
392
# Check server identity
393
print(f"Connected to: {plex.identity.friendlyName}")
394
print(f"Version: {plex.identity.version}")
395
```
396
397
### Content Search
398
399
```python
400
# Search all content
401
results = plex.search('star wars')
402
for item in results:
403
print(f"{item.title} ({item.type})")
404
405
# Search specific media type
406
movies = plex.search('matrix', mediatype='movie')
407
shows = plex.search('office', mediatype='show')
408
409
# Search within specific section
410
movie_section = plex.library.section('Movies')
411
section_results = plex.search('action', sectionId=movie_section.key)
412
```
413
414
### Server Administration
415
416
```python
417
# View active sessions
418
sessions = plex.sessions()
419
for session in sessions:
420
print(f"{session.user.title} watching {session.title}")
421
422
# Check server activities
423
activities = plex.activities()
424
for activity in activities:
425
print(f"{activity.title}: {activity.progress}%")
426
427
# Run maintenance task
428
tasks = plex.butlerTasks()
429
scanner_task = next(t for t in tasks if 'scan' in t.name.lower())
430
plex.runButlerTask(scanner_task)
431
```
432
433
### Settings Management
434
435
```python
436
# Access server settings
437
settings = plex.settings
438
friendly_name = settings.get('FriendlyName')
439
print(f"Server name: {friendly_name.value}")
440
441
# Modify setting
442
friendly_name.setValue('My Awesome Plex Server')
443
settings.save()
444
```
445
446
### User and Device Management
447
448
```python
449
# Get system accounts
450
accounts = plex.systemAccounts()
451
for account in accounts:
452
print(f"Account: {account.name} ({account.id})")
453
454
# Get connected devices
455
devices = plex.systemDevices()
456
for device in devices:
457
print(f"Device: {device.name} - {device.product}")
458
459
# Switch user context
460
admin_plex = plex.switchUser('admin')
461
print(f"Switched to user context: {admin_plex.account.title}")
462
463
# Get associated MyPlex account
464
myplex_account = plex.myPlexAccount()
465
if myplex_account:
466
print(f"Server linked to: {myplex_account.email}")
467
```
468
469
### Server Claiming
470
471
```python
472
from plexapi.myplex import MyPlexAccount
473
474
# Claim unclaimed server
475
account = MyPlexAccount('username', 'password')
476
unclaimed_plex = PlexServer('http://192.168.1.100:32400')
477
478
# Claim server with account
479
unclaimed_plex.claim(account)
480
print("Server claimed successfully")
481
482
# Later, unclaim if needed
483
plex.unclaim()
484
print("Server unclaimed")
485
```
486
487
### Filesystem Browsing
488
489
```python
490
# Browse server filesystem
491
root_items = plex.browse('/')
492
for item in root_items:
493
print(f"{'[DIR]' if item.container else '[FILE]'} {item.file}")
494
495
# Browse specific directory
496
media_items = plex.browse('/media/movies')
497
for item in media_items:
498
if not item.container: # Files only
499
print(f"File: {item.file} ({item.size} bytes)")
500
501
# Recursively walk filesystem
502
import os
503
for root, dirs, files in plex.walk('/media'):
504
level = root.replace('/media', '').count(os.sep)
505
indent = ' ' * 2 * level
506
print(f"{indent}{os.path.basename(root)}/")
507
508
subindent = ' ' * 2 * (level + 1)
509
for file in files[:5]: # Limit output
510
print(f"{subindent}{file}")
511
512
if len(files) > 5:
513
print(f"{subindent}... and {len(files) - 5} more files")
514
```
515
516
### Error Handling
517
518
```python
519
from plexapi.exceptions import BadRequest, NotFound, Unauthorized, TwoFactorRequired
520
from plexapi.server import PlexServer
521
from plexapi.myplex import MyPlexAccount
522
523
# Handle connection errors
524
try:
525
plex = PlexServer('http://localhost:32400', token='invalid-token')
526
except Unauthorized:
527
print("Invalid token - check your authentication credentials")
528
except BadRequest as e:
529
print(f"Server request failed: {e}")
530
531
# Handle MyPlex authentication errors
532
try:
533
account = MyPlexAccount('username', 'password')
534
except TwoFactorRequired:
535
code = input("Enter 2FA code: ")
536
account = MyPlexAccount('username', 'password', code=code)
537
except Unauthorized:
538
print("Invalid username/password combination")
539
540
# Handle missing resources
541
try:
542
server = account.resource('Nonexistent Server')
543
except NotFound:
544
print("Server not found - check server name")
545
available_servers = [r.name for r in account.resources()]
546
print(f"Available servers: {', '.join(available_servers)}")
547
548
# Handle client connection issues
549
try:
550
client = plex.client('Living Room TV')
551
client.connect()
552
except NotFound:
553
print("Client not found")
554
available_clients = [c.title for c in plex.clients()]
555
print(f"Available clients: {', '.join(available_clients)}")
556
except Exception as e:
557
print(f"Client connection failed: {e}")
558
```