PlexAPI Documentation

repository·master·Indexed 23 days ago

https://github.com/pushingkarmaorg/python-plexapi

Unofficial Python bindings for the Plex API designed to match the capabilities of the official Plex Web Client. The library enables developers to navigate libraries, perform server actions, control remote clients (including Sonos), and listen to server notifications. Documentation covers configuration via config files and environment variables, as well as detailed references for server settings including network, transcoder, library, and DLNA configurations.

Tokens
8.3K
Snippets
6
Records
47
Agent score
75%

What's inside PlexAPI

  1. Control Sonos speakers

    master

    To control Sonos speakers via the Plex API, you must have:

    1. An active Plex Pass subscription.
    2. A Sonos account linked to your Plex account.
    3. Plex remote access enabled.

    Control is performed through a PlexSonosPlayer instance obtained from a MyPlexAccount object. Note that media playback routes through https://sonos.plex.tv and back via the Plex server's remote access.

    from plexapi.myplex import MyPlexAccount
    from plexapi.server import PlexServer
    
    baseurl = 'http://plexserver:32400'
    token = '2ffLuB84dqLswk9skLos'
    
    account = MyPlexAccount(token)
    server = PlexServer(baseurl, token)
    
    # List available speakers
    for speaker in account.sonos_speakers():
        print(speaker.title)
    
    # Control a specific speaker
    speaker = account.sonos_speaker("Kitchen")
    album = server.library.section('Music').get('Stevie Wonder').album('Innervisions')
    
    speaker.playMedia(album)
    speaker.pause()
    speaker.setVolume(10)
    speaker.skipNext()
  2. Common PlexServer library operations

    master

    The PlexServer instance provides access to your media library and various playback controls. Here are common patterns:

    Searching and Filtering

    • List unwatched movies: Use plex.library.section('Movies').search(unwatched=True).
    • Search by title: Use plex.search('query') to search all content.
    • Filter by metadata: Search for content by specific attributes like director.

    Library Management

    • Marking content as played: Use .markPlayed() on a library item.
    • Rating content: Use .rate(rating) where rating is a float (e.g., 8.0 for 4 stars).
    • Accessing episodes: Use .episodes() on a show to get its episode list.

    Client and Playback Control

    • List connected clients: Use plex.clients().
    • Play media on a specific client: Use client.playMedia(media_item) where the client is obtained via plex.client("Client Name").
    # List unwatched movies
    movies = plex.library.section('Movies')
    for video in movies.search(unwatched=True):
        print(video.title)
    
    # Mark Game of Thrones as played
    plex.library.section('TV Shows').get('Game of Thrones').markPlayed()
    
    # List connected clients
    for client in plex.clients():
        print(client.title)
    
    # Play Cars on Michael's iPhone
    cars = plex.library.section('Movies').get('Cars')
    client = plex.client("Michael's iPhone")
    client.playMedia(cars)
    
    # Search for 'Game' in titles
    for video in plex.search('Game'):
        print(f'{video.title} ({video.TYPE})')
    
    # List movies by a specific director
    movies = plex.library.section('Movies')
    director = movies.get('Elephants Dream').directors[0]
    for movie in movies.search(None, director=director):
        print(movie.title)
    
    # Rate a show
    plex.library.section('TV Shows').get('The 100').rate(8.0)
  3. Configure Python-PlexAPI using a config file

    master

    Python-PlexAPI uses an optional configuration file to control default behaviors. The default location is ~/.config/plexapi/config.ini. You can override this default path by setting the PLEXAPI_CONFIG_PATH environment variable.

    An example config.ini structure is provided below. Note that all variables are optional.

    Security Warning: If you include sensitive information like myplex_password, server_token, or client_token in your config file, ensure the file permissions are restricted (e.g., chmod 600 ~/.config/plexapi/config.ini) so other users cannot read them.

    # ~/.config/plexapi/config.ini
    [plexapi]
    container_size = 50
    timeout = 30
    timezone = false
    
    [auth]
    myplex_username = johndoe
    myplex_password = kodi-stinks
    server_baseurl = http://127.0.0.1:32400
    server_token = XBHSMSJSDJ763JSm
    client_baseurl = http://127.0.0.1:32433
    client_token = BDFSLCNSNL789FH7
    
    [header]
    identifier = 0x485b314307f3L
    platorm = Linux
    platform_version = 4.4.0-62-generic
    product = PlexAPI
    version = 3.0.0
    
    [log]
    backup_count = 3
    format = %(asctime)s %(module)12s:%(lineno)-4s %(levelname)-9s %(message)s
    level = INFO
    path = ~/.config/plexapi/plexapi.log
    rotate_bytes = 512000
    show_secrets = false
  4. Install plexapi

    master

    Install the core library using pip:

    pip install plexapi

    For extra features, install with specific extras:

    • Alerts: Install dependencies required for plexapi.alert using pip install plexapi[alert].
    • JWT Authentication: Install dependencies required for Plex JWT authentication using pip install plexapi[jwt].
    pip install plexapi
    pip install plexapi[alert]
    pip install plexapi[jwt]
  5. Get a PlexServer instance

    master

    You can obtain a PlexServer instance using two different authentication methods:

    1. Using MyPlex Account

    If you are on a separate network or using Plex Users, log in via MyPlexAccount to find your server.

    2. Using Base URL and Auth Token

    If you already know your server's baseurl and token, you can instantiate PlexServer directly without logging into MyPlex.

    # Method 1: MyPlex
    from plexapi.myplex import MyPlexAccount
    account = MyPlexAccount('<USERNAME>', '<PASSWORD>')
    plex = account.resource('<SERVERNAME>').connect()
    
    # Method 2: Direct
    from plexapi.server import PlexServer
    baseurl = 'http://plexserver:32400'
    token = '2ffLuB84dqLswk9skLos'
    plex = PlexServer(baseurl, token)
  6. How to run tests for PlexAPI

    master

    Testing requires a running Plex instance and several environment variables.

    Environment Variables

    • PLEXAPI_AUTH_SERVER_BASEURL: URL to your Plex instance (e.g., http://127.0.0.1:32400).
    • PLEXAPI_AUTH_MYPLEX_USERNAME: Your MyPlex username.
    • PLEXAPI_AUTH_MYPLEX_PASSWORD: Your MyPlex password.
    • SHARED_USERNAME: (Optional) A valid shared user's username for specific tests.

    Running Tests

    1. Bootstrap tests: Use tools/plex-boostraptest.py to set up a test environment.
    2. Standard tests: Run py.test tests -rxXs --ignore=tests/test_sync.py.
    3. Mobile Sync tests: To test Mobile Sync, set the following environment variables exactly:
      • PLEXAPI_HEADER_PROVIDES='controller,sync-target'
      • PLEXAPI_HEADER_PLATFORM=iOS
      • PLEXAPI_HEADER_PLATFORM_VERSION=11.4.1
      • PLEXAPI_HEADER_DEVICE=iPhone Then run: py.test tests/test_sync.py -rxXs.
  7. How PlexClient and PlexServer interact

    master

    A PlexClient represents a specific player (like an iPhone or a Smart TV). It can operate in two modes:

    1. Direct Mode: The PlexClient communicates directly with the device's baseurl. This provides the most control but requires direct network access to the device.
    2. Proxy Mode: The PlexClient sends commands to the PlexServer, which then forwards them to the target client. This is enabled via proxyThroughServer(True).

    When initializing a PlexClient, you can provide a PlexServer instance to facilitate proxying or to share the underlying requests.Session.

  8. Configure Channels Settings

    master

    Settings related to server channels and plugins:

    • disableCapabilityChecking (bool): Disables checking for plugin compatibility. Useful for development, but may cause unreliable behavior.
    • iTunesLibraryXmlPath (text): Path to the iTunes library XML.
    • iTunesSharingEnabled (bool): Enable iTunes channel. Note: A server restart is required for changes to take effect.
    • pluginsLaunchTimeout (int): Seconds to wait before a plugin times out. Default: 180.