Python bindings for the Plex Media Server API, enabling programmatic interaction with Plex servers and media libraries.
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Core functionality for connecting to Plex Media Servers, managing server settings, accessing server information, and performing administrative tasks.
Primary class for connecting to and interacting with a Plex Media Server.
class PlexServer:
def __init__(self, baseurl=None, token=None, session=None, timeout=None):
"""
Connect to a Plex Media Server.
Args:
baseurl (str): Server URL (e.g., 'http://localhost:32400')
token (str): Authentication token
session (requests.Session, optional): HTTP session
timeout (int, optional): Request timeout in seconds
"""
def query(self, key, method=None, headers=None, params=None, timeout=None, **kwargs):
"""
Make raw API query to Plex server.
Args:
key (str): API endpoint path
method (str, optional): HTTP method (GET, POST, etc.)
headers (dict, optional): Additional HTTP headers
params (dict, optional): Query parameters
timeout (int, optional): Request timeout
Returns:
requests.Response: Raw HTTP response object
"""Access server information and core functionality.
class PlexServer:
@property
def library(self):
"""Library: Access to media library sections and content."""
@property
def settings(self):
"""Settings: Server configuration and settings management."""
@property
def account(self):
"""Account: Server account information and statistics."""
@property
def identity(self):
"""Identity: Server identity and version information."""Search across all server content and access various content views.
class PlexServer:
def search(self, query, mediatype=None, limit=None, sectionId=None):
"""
Search across all server content.
Args:
query (str): Search query string
mediatype (str, optional): Filter by media type ('movie', 'show', 'artist', etc.)
limit (int, optional): Maximum number of results
sectionId (int, optional): Search within specific library section
Returns:
list: List of matching media objects
"""
def sessions(self):
"""
Get active playback sessions.
Returns:
list: List of active session objects
"""
def history(self):
"""
Get server playback history.
Returns:
list: List of historical playback records
"""
def activities(self):
"""
Get background server activities.
Returns:
list: List of Activity objects representing background tasks
"""Access and control connected Plex clients.
class PlexServer:
def clients(self):
"""
Get all connected Plex clients.
Returns:
list: List of PlexClient objects
"""
def client(self, name):
"""
Get specific client by name.
Args:
name (str): Client name to find
Returns:
PlexClient: Client object for the specified name
Raises:
NotFound: If client with specified name is not found
"""Create and manage server-level playlists and collections.
class PlexServer:
def playlists(self):
"""
Get all server playlists.
Returns:
list: List of Playlist objects
"""
def createPlaylist(self, title, section=None, items=None, smart=False, limit=None, libtype=None, sort=None, filters=None, m3ufilepath=None, **kwargs):
"""
Create a new playlist.
Args:
title (str): Playlist title
section (LibrarySection, optional): Library section for smart playlists
items (list, optional): Initial items for regular playlists
smart (bool): Create smart playlist vs regular playlist
limit (int, optional): Limit number of items for smart playlists
libtype (str, optional): Media type for smart playlists ('movie', 'show', 'artist')
sort (str, optional): Sort order for smart playlists
filters (dict, optional): Filter criteria for smart playlists
m3ufilepath (str, optional): Path to M3U file to import
**kwargs: Additional playlist properties
Returns:
Playlist: Created playlist object
"""
def createCollection(self, title, section, items=None, smart=False, **kwargs):
"""
Create a new collection.
Args:
title (str): Collection title
section (LibrarySection): Target library section
items (list, optional): Initial collection items
smart (bool): Create smart collection vs regular collection
**kwargs: Additional collection properties
Returns:
Collection: Created collection object
"""
def createPlayQueue(self, item, **kwargs):
"""
Create a playback queue.
Args:
item: Media item to start queue with
**kwargs: Additional queue parameters
Returns:
PlayQueue: Created play queue object
"""Manage server users, devices, and administrative access.
class PlexServer:
def systemAccounts(self):
"""
Get server system accounts.
Returns:
list: List of system account objects
"""
def systemDevices(self):
"""
Get connected system devices.
Returns:
list: List of system device objects
"""
def switchUser(self, username):
"""
Switch to different user context on server.
Args:
username (str): Username to switch to
Returns:
PlexServer: Server instance with new user context
"""
def myPlexAccount(self):
"""
Get associated MyPlex account for this server.
Returns:
MyPlexAccount: Associated account object
"""
def claim(self, account):
"""
Claim unclaimed server with MyPlex account.
Args:
account (MyPlexAccount): Account to claim server with
"""
def unclaim(self):
"""Unclaim server from MyPlex account."""Browse and navigate server filesystem through Plex API.
class PlexServer:
def browse(self, path='/'):
"""
Browse server filesystem at specified path.
Args:
path (str): Filesystem path to browse
Returns:
list: List of filesystem items (directories and files)
"""
def walk(self, path='/'):
"""
Recursively walk server filesystem starting at path.
Args:
path (str): Starting path for filesystem walk
Yields:
tuple: (dirpath, dirnames, filenames) for each directory
"""Perform server maintenance and administrative tasks.
class PlexServer:
def refreshContent(self):
"""Refresh all server content metadata."""
def butlerTasks(self):
"""
Get available maintenance tasks.
Returns:
list: List of ButlerTask objects
"""
def runButlerTask(self, task):
"""
Execute a maintenance task.
Args:
task (str or ButlerTask): Task name or task object to execute
"""Access detailed server information and statistics.
class Account:
"""Server account information and statistics."""
@property
def id(self): ...
@property
def title(self): ...
@property
def thumb(self): ...
class Identity:
"""Server identity and version information."""
@property
def machineIdentifier(self): ...
@property
def version(self): ...
@property
def platform(self): ...
class Activity:
"""Background server activity or task."""
@property
def title(self): ...
@property
def type(self): ...
@property
def progress(self): ...
class ButlerTask:
"""Server maintenance task."""
@property
def name(self): ...
@property
def title(self): ...
@property
def description(self): ...Configure server settings and preferences.
class Settings:
"""Server settings interface."""
def get(self, key):
"""
Get setting value by key.
Args:
key (str): Setting key name
Returns:
Setting: Setting object with current value
"""
def save(self):
"""Save any modified settings to server."""
class Setting:
"""Individual server setting."""
@property
def id(self): ...
@property
def label(self): ...
@property
def value(self): ...
def setValue(self, value):
"""Set new value for this setting."""from plexapi.server import PlexServer
# Direct connection with token
plex = PlexServer('http://192.168.1.100:32400', 'your-auth-token')
# Check server identity
print(f"Connected to: {plex.identity.friendlyName}")
print(f"Version: {plex.identity.version}")# Search all content
results = plex.search('star wars')
for item in results:
print(f"{item.title} ({item.type})")
# Search specific media type
movies = plex.search('matrix', mediatype='movie')
shows = plex.search('office', mediatype='show')
# Search within specific section
movie_section = plex.library.section('Movies')
section_results = plex.search('action', sectionId=movie_section.key)# View active sessions
sessions = plex.sessions()
for session in sessions:
print(f"{session.user.title} watching {session.title}")
# Check server activities
activities = plex.activities()
for activity in activities:
print(f"{activity.title}: {activity.progress}%")
# Run maintenance task
tasks = plex.butlerTasks()
scanner_task = next(t for t in tasks if 'scan' in t.name.lower())
plex.runButlerTask(scanner_task)# Access server settings
settings = plex.settings
friendly_name = settings.get('FriendlyName')
print(f"Server name: {friendly_name.value}")
# Modify setting
friendly_name.setValue('My Awesome Plex Server')
settings.save()# Get system accounts
accounts = plex.systemAccounts()
for account in accounts:
print(f"Account: {account.name} ({account.id})")
# Get connected devices
devices = plex.systemDevices()
for device in devices:
print(f"Device: {device.name} - {device.product}")
# Switch user context
admin_plex = plex.switchUser('admin')
print(f"Switched to user context: {admin_plex.account.title}")
# Get associated MyPlex account
myplex_account = plex.myPlexAccount()
if myplex_account:
print(f"Server linked to: {myplex_account.email}")from plexapi.myplex import MyPlexAccount
# Claim unclaimed server
account = MyPlexAccount('username', 'password')
unclaimed_plex = PlexServer('http://192.168.1.100:32400')
# Claim server with account
unclaimed_plex.claim(account)
print("Server claimed successfully")
# Later, unclaim if needed
plex.unclaim()
print("Server unclaimed")# Browse server filesystem
root_items = plex.browse('/')
for item in root_items:
print(f"{'[DIR]' if item.container else '[FILE]'} {item.file}")
# Browse specific directory
media_items = plex.browse('/media/movies')
for item in media_items:
if not item.container: # Files only
print(f"File: {item.file} ({item.size} bytes)")
# Recursively walk filesystem
import os
for root, dirs, files in plex.walk('/media'):
level = root.replace('/media', '').count(os.sep)
indent = ' ' * 2 * level
print(f"{indent}{os.path.basename(root)}/")
subindent = ' ' * 2 * (level + 1)
for file in files[:5]: # Limit output
print(f"{subindent}{file}")
if len(files) > 5:
print(f"{subindent}... and {len(files) - 5} more files")from plexapi.exceptions import BadRequest, NotFound, Unauthorized, TwoFactorRequired
from plexapi.server import PlexServer
from plexapi.myplex import MyPlexAccount
# Handle connection errors
try:
plex = PlexServer('http://localhost:32400', token='invalid-token')
except Unauthorized:
print("Invalid token - check your authentication credentials")
except BadRequest as e:
print(f"Server request failed: {e}")
# Handle MyPlex authentication errors
try:
account = MyPlexAccount('username', 'password')
except TwoFactorRequired:
code = input("Enter 2FA code: ")
account = MyPlexAccount('username', 'password', code=code)
except Unauthorized:
print("Invalid username/password combination")
# Handle missing resources
try:
server = account.resource('Nonexistent Server')
except NotFound:
print("Server not found - check server name")
available_servers = [r.name for r in account.resources()]
print(f"Available servers: {', '.join(available_servers)}")
# Handle client connection issues
try:
client = plex.client('Living Room TV')
client.connect()
except NotFound:
print("Client not found")
available_clients = [c.title for c in plex.clients()]
print(f"Available clients: {', '.join(available_clients)}")
except Exception as e:
print(f"Client connection failed: {e}")Install with Tessl CLI
npx tessl i tessl/pypi-plex-api