* `plex_api.library_playlists.add_playlist_items()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.hubs.get_metadata_hubs()`: * `request.only_transient` **Changed** * `response.media_container.hub.[].metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library_collections.move_collection_item()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library_collections.delete_collection_item()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library_collections.add_collection_items()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.content.get_sonically_similar()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.butler.stop_task()`: `request` **Changed** **Breaking** ⚠️ * `plex_api.butler.start_task()`: `request` **Changed** **Breaking** ⚠️ * `plex_api.content.get_sonic_path()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.download_queue.get_item_decision()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.hubs.get_all_hubs()`: * `request.only_transient` **Changed** * `response.media_container.hub.[].metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.hubs.get_continue_watching()`: `response.media_container.hub.[].metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.hubs.get_promoted_hubs()`: `response.media_container.hub.[].metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.content.get_all_leaves()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.hubs.get_postplay_hubs()`: * `request.only_transient` **Changed** * `response.media_container.hub.[].metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.hubs.get_related_hubs()`: * `request.only_transient` **Changed** * `response.media_container.hub.[].metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.hubs.get_section_hubs()`: * `request.only_transient` **Changed** * `response.media_container.hub.[].metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.content.list_content()`: * `request` **Changed** * `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.content.get_albums()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.search.search_hubs()`: `response.media_container.hub.[].metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.search.voice_search_hubs()`: * `request.type` **Changed** **Breaking** ⚠️ * `response.media_container.hub.[].metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.get_library_items()`: * `request.media_query` **Changed** * `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.ingest_transient_item()`: * `request` **Changed** * `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.get_library_matches()`: * `request` **Changed** **Breaking** ⚠️ * `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.content.get_metadata_item()`: * `request` **Changed** * `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.get_sections()`: `response.media_container.directory.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.add_section()`: * `request` **Changed** * `response.media_container.directory.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.get_tags()`: * `request.type` **Changed** **Breaking** ⚠️ * `plex_api.content.get_collection_items()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.get_all_item_leaves()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.status.list_sessions()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.play_queue.move_play_queue_item()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.get_extras()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.play_queue.delete_play_queue_item()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.play_queue.unshuffle()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.list_matches()`: * `request.manual` **Changed** * `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.list_sonically_similar()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.play_queue.reset_play_queue()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.get_related_items()`: `response.media_container.hub.[].metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.list_similar()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.play_queue.clear_play_queue()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.get_item_tree()`: `response.media_container.metadata_item.[]` **Changed** **Breaking** ⚠️ * `plex_api.play_queue.add_to_play_queue()`: * `request.next` **Changed** * `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.play_queue.get_play_queue()`: * `request` **Changed** * `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library_playlists.move_playlist_item()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.get_person()`: `response.media_container.directory.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.list_person_media()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library_playlists.get_playlist_generator_items()`: `response.media_container.metadata` **Changed** **Breaking** ⚠️ * `plex_api.library.get_library_details()`: * `request.include_details` **Changed** * `response.media_container.directory.[]` **Changed** **Breaking** ⚠️ * `plex_api.library_playlists.modify_playlist_generator()`: * `request.item` **Changed** * `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.autocomplete()`: * `request.media_query` **Changed** * `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.get_collections()`: * `request.media_query` **Changed** * `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.get_common()`: * `request.media_query` **Changed** * `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library_playlists.delete_playlist_item()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library_playlists.clear_playlist_items()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.play_queue.shuffle()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library_playlists.create_playlist()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.playlist.get_playlist_items()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.playlist.get_playlist()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.collections.create_collection()`: * `request.type` **Changed** **Breaking** ⚠️ * `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.dv_rs.tune_channel()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.live_tv.get_sessions()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.live_tv.get_live_tv_session()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.playlist.list_playlists()`: `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.subscriptions.get_all_subscriptions()`: * `request` **Changed** * `response.media_container.media_subscription.[].media_grab_operation.[].metadata` **Changed** **Breaking** ⚠️ * `plex_api.subscriptions.create_subscription()`: `response.media_container.media_subscription.[].media_grab_operation.[].metadata` **Changed** **Breaking** ⚠️ * `plex_api.subscriptions.get_scheduled_recordings()`: `response.media_container.media_grab_operation.[].metadata` **Changed** **Breaking** ⚠️ * `plex_api.subscriptions.get_template()`: `response.media_container.subscription_template.[].media_subscription.[].media_grab_operation.[].metadata` **Changed** **Breaking** ⚠️ * `plex_api.subscriptions.get_subscription()`: * `request` **Changed** * `response.media_container.media_subscription.[].media_grab_operation.[].metadata` **Changed** **Breaking** ⚠️ * `plex_api.subscriptions.edit_subscription_preferences()`: `response.media_container.media_subscription.[].media_grab_operation.[].metadata` **Changed** **Breaking** ⚠️ * `plex_api.subscriptions.reorder_subscription()`: `response.media_container.media_subscription.[].media_grab_operation.[].metadata` **Changed** **Breaking** ⚠️ * `plex_api.transcoder.make_decision()`: * `request` **Changed** * `response.media_container.metadata.[]` **Changed** **Breaking** ⚠️ * `plex_api.library.refresh_items_metadata()`: * `request.mark_updated` **Changed** * `plex_api.authentication.post-users-sign-in-data()`: **Added** * `plex_api.transcoder.start_transcode_session()`: `request` **Changed** * `plex_api.devices.modify_device()`: * `request.enabled` **Changed** * `plex_api.library.get_media_part()`: * `request.download` **Changed** * `plex_api.library.detect_intros()`: * `request.force` **Changed** * `plex_api.library.refresh_section()`: * `request.force` **Changed** * `plex_api.library_playlists.upload_playlist()`: * `request.force` **Changed** * `plex_api.library.delete_media_item()`: * `request.proxy` **Changed** * `plex_api.authentication.get_token_details()`: **Added** * `plex_api.library.get_first_characters()`: * `request.media_query` **Changed** * `plex_api.library.update_items()`: * `request.field.locked` **Changed** * `plex_api.library.delete_library_section()`: * `request.async` **Changed** * `plex_api.library.set_stream_selection()`: * `request.all_parts` **Changed** * `plex_api.play_queue.create_play_queue()`: `request` **Changed** * `plex_api.library.get_augmentation_status()`: * `request.wait` **Changed** * `plex_api.library.detect_voice_activity()`: `request` **Changed** * `plex_api.transcoder.transcode_image()`: `request` **Changed** * `plex_api.transcoder.transcode_subtitles()`: `request` **Changed** * `plex_api.library.add_subtitles()`: `request` **Changed** * `plex_api.library.get_stream()`: * `request.auto_adjust_subtitle` **Changed** * `plex_api.library.start_bif_generation()`: * `request.force` **Changed** * `plex_api.library.detect_credits()`: `request` **Changed** * `plex_api.ultra_blur.get_image()`: * `request.noise` **Changed** * `plex_api.library.generate_thumbs()`: * `request.force` **Changed** * `plex_api.updater.apply_updates()`: `request` **Changed** * `plex_api.updater.check_updates()`: * `request.download` **Changed** * `plex_api.library.delete_metadata_item()`: * `request.proxy` **Changed** * `plex_api.library.optimize_database()`: * `request.async` **Changed** * `plex_api.hubs.update_hub_visibility()`: `request` **Changed** * `plex_api.hubs.create_custom_hub()`: `request` **Changed** * `plex_api.library.get_section_image()`: * `request.media_query` **Changed** * `plex_api.download_queue.add_download_queue_items()`: `request` **Changed** * `plex_api.timeline.report()`: `request` **Changed** * `plex_api.general.get_source_connection_information()`: * `request.refresh` **Changed** * `plex_api.plex.get-server-resources()`: **Added** * `plex_api.users.get-users()`: **Added**
plexpy
Summary
Table of Contents
SDK Installation
Note
Python version upgrade policy
Once a Python version reaches its official end of life date, a 3-month grace period is provided for users to upgrade. Following this grace period, the minimum python version supported in the SDK will be updated.
The SDK can be installed with uv, pip, or poetry package managers.
uv
uv is a fast Python package installer and resolver, designed as a drop-in replacement for pip and pip-tools. It's recommended for its speed and modern Python tooling capabilities.
uv add plex-api-client
PIP
PIP is the default package installer for Python, enabling easy installation and management of packages from PyPI via the command line.
pip install plex-api-client
Poetry
Poetry is a modern tool that simplifies dependency management and package publishing by using a single pyproject.toml file to handle project metadata and dependencies.
poetry add plex-api-client
Shell and script usage with uv
You can use this SDK in a Python shell with uv and the uvx command that comes with it like so:
uvx --from plex-api-client python
It's also possible to write a standalone Python script without needing to set up a whole project like so:
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.9"
# dependencies = [
# "plex-api-client",
# ]
# ///
from plex_api_client import PlexAPI
sdk = PlexAPI(
# SDK arguments
)
# Rest of script here...
Once that is saved to a file, you can run it with uv run script.py where
script.py can be replaced with the actual file name.
IDE Support
PyCharm
Generally, the SDK will work well with most IDEs out of the box. However, when using PyCharm, you can enjoy much better integration with Pydantic by installing an additional plugin.
SDK Example Usage
Example
# Synchronous Example
from plex_api_client import PlexAPI
from plex_api_client.models import components, operations
with PlexAPI(
accepts=components.Accepts.APPLICATION_XML,
client_identifier="abc123",
product="Plex for Roku",
version="2.4.1",
platform="Roku",
platform_version="4.3 build 1057",
device="Roku 3",
model="4200X",
device_vendor="Roku",
device_name="Living Room TV",
marketplace="googlePlay",
token="<YOUR_API_KEY_HERE>",
) as plex_api:
res = plex_api.transcoder.start_transcode_session(request=operations.StartTranscodeSessionRequest(
transcode_type=components.TranscodeType.MUSIC,
extension=operations.Extension.MPD,
advanced_subtitles=components.AdvancedSubtitles.BURN,
audio_boost=50,
audio_channel_count=5,
auto_adjust_quality=components.BoolInt.TRUE,
auto_adjust_subtitle=components.BoolInt.TRUE,
direct_play=components.BoolInt.TRUE,
direct_stream=components.BoolInt.TRUE,
direct_stream_audio=components.BoolInt.TRUE,
disable_resolution_rotation=components.BoolInt.TRUE,
has_mde=components.BoolInt.TRUE,
location=operations.StartTranscodeSessionQueryParamLocation.WAN,
media_buffer_size=102400,
media_index=0,
music_bitrate=5000,
offset=90.5,
part_index=0,
path="/library/metadata/151671",
peak_bitrate=12000,
photo_resolution="1080x1080",
protocol=operations.StartTranscodeSessionQueryParamProtocol.DASH,
seconds_per_segment=5,
subtitle_size=50,
video_bitrate=12000,
video_quality=50,
video_resolution="1080x1080",
x_plex_client_profile_extra="add-limitation(scope=videoCodec&scopeName=*&type=upperBound&name=video.frameRate&value=60&replace=true)+append-transcode-target-codec(type=videoProfile&context=streaming&videoCodec=h264%2Chevc&audioCodec=aac&protocol=dash)",
x_plex_client_profile_name="generic",
))
assert res.response_stream is not None
# Handle response
print(res.response_stream)
The same SDK client can also be used to make asynchronous requests by importing asyncio.
# Asynchronous Example
import asyncio
from plex_api_client import PlexAPI
from plex_api_client.models import components, operations
async def main():
async with PlexAPI(
accepts=components.Accepts.APPLICATION_XML,
client_identifier="abc123",
product="Plex for Roku",
version="2.4.1",
platform="Roku",
platform_version="4.3 build 1057",
device="Roku 3",
model="4200X",
device_vendor="Roku",
device_name="Living Room TV",
marketplace="googlePlay",
token="<YOUR_API_KEY_HERE>",
) as plex_api:
res = await plex_api.transcoder.start_transcode_session_async(request=operations.StartTranscodeSessionRequest(
transcode_type=components.TranscodeType.MUSIC,
extension=operations.Extension.MPD,
advanced_subtitles=components.AdvancedSubtitles.BURN,
audio_boost=50,
audio_channel_count=5,
auto_adjust_quality=components.BoolInt.TRUE,
auto_adjust_subtitle=components.BoolInt.TRUE,
direct_play=components.BoolInt.TRUE,
direct_stream=components.BoolInt.TRUE,
direct_stream_audio=components.BoolInt.TRUE,
disable_resolution_rotation=components.BoolInt.TRUE,
has_mde=components.BoolInt.TRUE,
location=operations.StartTranscodeSessionQueryParamLocation.WAN,
media_buffer_size=102400,
media_index=0,
music_bitrate=5000,
offset=90.5,
part_index=0,
path="/library/metadata/151671",
peak_bitrate=12000,
photo_resolution="1080x1080",
protocol=operations.StartTranscodeSessionQueryParamProtocol.DASH,
seconds_per_segment=5,
subtitle_size=50,
video_bitrate=12000,
video_quality=50,
video_resolution="1080x1080",
x_plex_client_profile_extra="add-limitation(scope=videoCodec&scopeName=*&type=upperBound&name=video.frameRate&value=60&replace=true)+append-transcode-target-codec(type=videoProfile&context=streaming&videoCodec=h264%2Chevc&audioCodec=aac&protocol=dash)",
x_plex_client_profile_name="generic",
))
assert res.response_stream is not None
# Handle response
print(res.response_stream)
asyncio.run(main())
Available Resources and Operations
Available methods
activities
- list_activities - Get all activities
- cancel_activity - Cancel a running activity
authentication
- get_token_details - Get Token Details
- post_users_sign_in_data - Get User Sign In Data
butler
- stop_tasks - Stop all Butler tasks
- get_tasks - Get all Butler tasks
- start_tasks - Start all Butler tasks
- stop_task - Stop a single Butler task
- start_task - Start a single Butler task
collections
- create_collection - Create collection
content
- get_collection_items - Get items in a collection
- get_metadata_item - Get a metadata item
- get_albums - Set section albums
- list_content - Get items in the section
- get_all_leaves - Set section leaves
- get_arts - Set section artwork
- get_categories - Set section categories
- get_cluster - Set section clusters
- get_sonic_path - Similar tracks to transition from one to another
- get_folders - Get all folder locations
- list_moments - Set section moments
- get_sonically_similar - The nearest audio tracks
- get_collection_image - Get a collection's image
devices
- get_available_grabbers - Get available grabbers
- list_devices - Get all devices
- add_device - Add a device
- discover_devices - Tell grabbers to discover devices
- remove_device - Remove a device
- get_device_details - Get device details
- modify_device - Enable or disable a device
- set_channelmap - Set a device's channel mapping
- get_devices_channels - Get a device's channels
- set_device_preferences - Set device preferences
- stop_scan - Tell a device to stop scanning for channels
- scan - Tell a device to scan for channels
- get_thumb - Get device thumb
download_queue
- create_download_queue - Create download queue
- get_download_queue - Get a download queue
- add_download_queue_items - Add to download queue
- list_download_queue_items - Get download queue items
- get_item_decision - Grab download queue item decision
- get_download_queue_media - Grab download queue media
- remove_download_queue_items - Delete download queue items
- get_download_queue_items - Get download queue items
- restart_processing_download_queue_items - Restart processing of items from the decision
dv_rs
- list_dv_rs - Get DVRs
- create_dvr - Create a DVR
- delete_dvr - Delete a single DVR
- get_dvr - Get a single DVR
- delete_lineup - Delete a DVR Lineup
- add_lineup - Add a DVR Lineup
- set_dvr_preferences - Set DVR preferences
- stop_dvr_reload - Tell a DVR to stop reloading program guide
- reload_guide - Tell a DVR to reload program guide
- tune_channel - Tune a channel on a DVR
- remove_device_from_dvr - Remove a device from an existing DVR
- add_device_to_dvr - Add a device to an existing DVR
epg
- compute_channel_map - Compute the best channel map
- get_channels - Get channels for a lineup
- get_countries - Get all countries
- get_all_languages - Get all languages
- get_lineup - Compute the best lineup
- get_lineup_channels - Get the channels for mulitple lineups
- get_countries_lineups - Get lineups for a country via postal code
- get_country_regions - Get regions for a country
- list_lineups - Get lineups for a region
events
- get_notifications - Connect to Eventsource
- connect_web_socket - Connect to WebSocket
general
- get_server_info - Get PMS info
- get_identity - Get PMS identity
- get_source_connection_information - Get Source Connection Information
- get_transient_token - Get Transient Tokens
hubs
- get_all_hubs - Get global hubs
- get_continue_watching - Get the continue watching hub
- get_hub_items - Get a hub's items
- get_promoted_hubs - Get the hubs which are promoted
- get_metadata_hubs - Get hubs for section by metadata item
- get_postplay_hubs - Get postplay hubs
- get_related_hubs - Get related hubs
- get_section_hubs - Get section hubs
- reset_section_defaults - Reset hubs to defaults
- list_hubs - Get hubs
- create_custom_hub - Create a custom hub
- move_hub - Move Hub
- delete_custom_hub - Delete a custom hub
- update_hub_visibility - Change hub visibility
library
- get_library_items - Get all items in library
- delete_caches - Delete library caches
- clean_bundles - Clean bundles
- ingest_transient_item - Ingest a transient item
- get_library_matches - Get library matches
- optimize_database - Optimize the Database
- get_random_artwork - Get random artwork
- get_sections - Get library sections (main Media Provider Only)
- add_section - Add a library section
- stop_all_refreshes - Stop refresh
- get_sections_prefs - Get section prefs
- refresh_sections_metadata - Refresh all sections
- get_tags - Get all library tags of a type
- delete_metadata_item - Delete a metadata item
- edit_metadata_item - Edit a metadata item
- detect_ads - Ad-detect an item
- get_all_item_leaves - Get the leaves of an item
- analyze_metadata - Analyze an item
- generate_thumbs - Generate thumbs of chapters for an item
- detect_credits - Credit detect a metadata item
- get_extras - Get an item's extras
- add_extras - Add to an item's extras
- get_file - Get a file from a metadata or media bundle
- start_bif_generation - Start BIF generation of an item
- detect_intros - Intro detect an item
- create_marker - Create a marker
- match_item - Match a metadata item
- list_matches - Get metadata matches for an item
- merge_items - Merge a metadata item
- list_sonically_similar - Get nearest tracks to metadata item
- set_item_preferences - Set metadata preferences
- refresh_items_metadata - Refresh a metadata item
- get_related_items - Get related items
- list_similar - Get similar items
- split_item - Split a metadata item
- add_subtitles - Add subtitles
- get_item_tree - Get metadata items as a tree
- unmatch - Unmatch a metadata item
- list_top_users - Get metadata top users
- detect_voice_activity - Detect voice activity
- get_augmentation_status - Get augmentation status
- set_stream_selection - Set stream selection
- get_person - Get person details
- list_person_media - Get media for a person
- delete_library_section - Delete a library section
- get_library_details - Get a library section by id
- edit_section - Edit a library section
- update_items - Set the fields of the filtered items
- start_analysis - Analyze a section
- autocomplete - Get autocompletions for search
- get_collections - Get collections in a section
- get_common - Get common fields for items
- empty_trash - Empty section trash
- get_section_filters - Get section filters
- get_first_characters - Get list of first characters
- delete_indexes - Delete section indexes
- delete_intros - Delete section intro markers
- get_section_preferences - Get section prefs
- set_section_preferences - Set section prefs
- cancel_refresh - Cancel section refresh
- refresh_section - Refresh section
- get_available_sorts - Get a section sorts
- get_stream_levels - Get loudness about a stream in json
- get_stream_loudness - Get loudness about a stream
- get_chapter_image - Get a chapter image
- set_item_artwork - Set an item's artwork, theme, etc
- update_item_artwork - Set an item's artwork, theme, etc
- delete_marker - Delete a marker
- edit_marker - Edit a marker
- delete_media_item - Delete a media item
- get_part_index - Get BIF index for a part
- delete_collection - Delete a collection
- get_section_image - Get a section composite image
- delete_stream - Delete a stream
- get_stream - Get a stream
- set_stream_offset - Set a stream offset
- get_item_artwork - Get an item's artwork, theme, etc
- get_media_part - Get a media part
- get_image_from_bif - Get an image from part BIF
library_collections
- add_collection_items - Add items to a collection
- delete_collection_item - Delete an item from a collection
- move_collection_item - Reorder an item in the collection
library_playlists
- create_playlist - Create a Playlist
- upload_playlist - Upload
- delete_playlist - Delete a Playlist
- update_playlist - Editing a Playlist
- get_playlist_generators - Get a playlist's generators
- clear_playlist_items - Clearing a playlist
- add_playlist_items - Adding to a Playlist
- delete_playlist_item - Delete a Generator
- get_playlist_generator - Get a playlist generator
- modify_playlist_generator - Modify a Generator
- get_playlist_generator_items - Get a playlist generator's items
- move_playlist_item - Moving items in a playlist
- refresh_playlist - Reprocess a generator
live_tv
- get_sessions - Get all sessions
- get_live_tv_session - Get a single session
- get_session_playlist_index - Get a session playlist index
- get_session_segment - Get a single session segment
log
- write_log - Logging a multi-line message to the Plex Media Server log
- write_message - Logging a single-line message to the Plex Media Server log
- enable_papertrail - Enabling Papertrail
play_queue
- create_play_queue - Create a play queue
- get_play_queue - Retrieve a play queue
- add_to_play_queue - Add a generator or playlist to a play queue
- clear_play_queue - Clear a play queue
- reset_play_queue - Reset a play queue
- shuffle - Shuffle a play queue
- unshuffle - Unshuffle a play queue
- delete_play_queue_item - Delete an item from a play queue
- move_play_queue_item - Move an item in a play queue
playlist
- list_playlists - List playlists
- get_playlist - Retrieve Playlist
- get_playlist_items - Retrieve Playlist Contents
plex
- get_server_resources - Get Server Resources
preferences
- get_all_preferences - Get all preferences
- set_preferences - Set preferences
- get_preference - Get a preferences
provider
- list_providers - Get the list of available media providers
- add_provider - Add a media provider
- refresh_providers - Refresh media providers
- delete_media_provider - Delete a media provider
rate
- set_rating - Rate an item
search
- search_hubs - Search Hub
- voice_search_hubs - Voice Search Hub
status
- list_sessions - List Sessions
- get_background_tasks - Get background tasks
- list_playback_history - List Playback History
- terminate_session - Terminate a session
- delete_history - Delete Single History Item
- get_history_item - Get Single History Item
subscriptions
- get_all_subscriptions - Get all subscriptions
- create_subscription - Create a subscription
- process_subscriptions - Process all subscriptions
- get_scheduled_recordings - Get all scheduled recordings
- get_template - Get the subscription template
- cancel_grab - Cancel an existing grab
- delete_subscription - Delete a subscription
- get_subscription - Get a single subscription
- edit_subscription_preferences - Edit a subscription
- reorder_subscription - Re-order a subscription
timeline
- mark_played - Mark an item as played
- report - Report media timeline
- unscrobble - Mark an item as unplayed
transcoder
- transcode_image - Transcode an image
- make_decision - Make a decision on media playback
- trigger_fallback - Manually trigger a transcoder fallback
- transcode_subtitles - Transcode subtitles
- start_transcode_session - Start A Transcoding Session
ultra_blur
- get_colors - Get UltraBlur Colors
- get_image - Get UltraBlur Image
updater
- apply_updates - Applying updates
- check_updates - Checking for updates
- get_updates_status - Querying status of updates
users
- get_users - Get list of all connected users
File uploads
Certain SDK methods accept file objects as part of a request body or multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request.
Tip
For endpoints that handle file uploads bytes arrays can also be used. However, using streams is recommended for large files.
from plex_api_client import PlexAPI
with PlexAPI(
token="<YOUR_API_KEY_HERE>",
) as plex_api:
res = plex_api.log.write_log(request=open("example.file", "rb"))
assert res is not None
# Handle response
print(res)
Retries
Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a RetryConfig object to the call:
from plex_api_client import PlexAPI
from plex_api_client.models import components
from plex_api_client.utils import BackoffStrategy, RetryConfig
with PlexAPI(
accepts=components.Accepts.APPLICATION_XML,
client_identifier="abc123",
product="Plex for Roku",
version="2.4.1",
platform="Roku",
platform_version="4.3 build 1057",
device="Roku 3",
model="4200X",
device_vendor="Roku",
device_name="Living Room TV",
marketplace="googlePlay",
token="<YOUR_API_KEY_HERE>",
) as plex_api:
res = plex_api.general.get_server_info(request={},
RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False))
assert res.media_container_with_directory is not None
# Handle response
print(res.media_container_with_directory)
If you'd like to override the default retry strategy for all operations that support retries, you can use the retry_config optional parameter when initializing the SDK:
from plex_api_client import PlexAPI
from plex_api_client.models import components
from plex_api_client.utils import BackoffStrategy, RetryConfig
with PlexAPI(
retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
accepts=components.Accepts.APPLICATION_XML,
client_identifier="abc123",
product="Plex for Roku",
version="2.4.1",
platform="Roku",
platform_version="4.3 build 1057",
device="Roku 3",
model="4200X",
device_vendor="Roku",
device_name="Living Room TV",
marketplace="googlePlay",
token="<YOUR_API_KEY_HERE>",
) as plex_api:
res = plex_api.general.get_server_info(request={})
assert res.media_container_with_directory is not None
# Handle response
print(res.media_container_with_directory)
Error Handling
PlexAPIError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
|---|---|---|
err.message |
str |
Error message |
err.status_code |
int |
HTTP response status code eg 404 |
err.headers |
httpx.Headers |
HTTP response headers |
err.body |
str |
HTTP body. Can be empty string if no body is returned. |
err.raw_response |
httpx.Response |
Raw HTTP response |
err.data |
Optional. Some errors may contain structured data. See Error Classes. |
Example
from plex_api_client import PlexAPI
from plex_api_client.models import components, errors
with PlexAPI(
accepts=components.Accepts.APPLICATION_XML,
client_identifier="abc123",
product="Plex for Roku",
version="2.4.1",
platform="Roku",
platform_version="4.3 build 1057",
device="Roku 3",
model="4200X",
device_vendor="Roku",
device_name="Living Room TV",
marketplace="googlePlay",
token="<YOUR_API_KEY_HERE>",
) as plex_api:
res = None
try:
res = plex_api.authentication.get_token_details(request={})
assert res.user_plex_account is not None
# Handle response
print(res.user_plex_account)
except errors.PlexAPIError as e:
# The base class for HTTP error responses
print(e.message)
print(e.status_code)
print(e.body)
print(e.headers)
print(e.raw_response)
# Depending on the method different errors may be thrown
if isinstance(e, errors.GetTokenDetailsBadRequest):
print(e.data.errors) # Optional[List[errors.Errors]]
print(e.data.raw_response) # Optional[httpx.Response]
Error Classes
Primary error:
PlexAPIError: The base class for HTTP error responses.
Less common errors (12)
Network errors:
httpx.RequestError: Base class for request errors.httpx.ConnectError: HTTP client was unable to make a request to a server.httpx.TimeoutException: HTTP request timed out.
Inherit from PlexAPIError:
GetTokenDetailsBadRequest: Bad Request - A parameter was not specified, or was specified incorrectly. Status code400. Applicable to 1 of 241 methods.*PostUsersSignInDataBadRequest: Bad Request - A parameter was not specified, or was specified incorrectly. Status code400. Applicable to 1 of 241 methods.*GetUsersBadRequest: Bad Request - A parameter was not specified, or was specified incorrectly. Status code400. Applicable to 1 of 241 methods.*GetTokenDetailsUnauthorized: Unauthorized - Returned if the X-Plex-Token is missing from the header or query. Status code401. Applicable to 1 of 241 methods.*PostUsersSignInDataUnauthorized: Unauthorized - Returned if the X-Plex-Token is missing from the header or query. Status code401. Applicable to 1 of 241 methods.*GetUsersUnauthorized: Unauthorized - Returned if the X-Plex-Token is missing from the header or query. Status code401. Applicable to 1 of 241 methods.*GetServerResourcesUnauthorized: Unauthorized - Returned if the X-Plex-Token is missing from the header or query. Status code401. Applicable to 1 of 241 methods.*ResponseValidationError: Type mismatch between the response data and the expected Pydantic model. Provides access to the Pydantic validation error via thecauseattribute.
* Check the method documentation to see if the error is applicable.
Server Selection
Select Server by Index
You can override the default server globally by passing a server index to the server_idx: int optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the indexes associated with the available servers:
| # | Server | Variables | Description |
|---|---|---|---|
| 0 | https://{IP-description}.{identifier}.plex.direct:{port} |
identifierIP-descriptionport |
|
| 1 | {protocol}://{host}:{port} |
protocolhostport |
|
| 2 | https://{full_server_url} |
full_server_url |
If the selected server has variables, you may override its default values through the additional parameters made available in the SDK constructor:
| Variable | Parameter | Default | Description |
|---|---|---|---|
identifier |
identifier: str |
"0123456789abcdef0123456789abcdef" |
The unique identifier of this particular PMS |
IP-description |
ip_description: str |
"1-2-3-4" |
A - separated string of the IPv4 or IPv6 address components |
port |
port: str |
"32400" |
The Port number configured on the PMS. Typically (32400). If using a reverse proxy, this would be the port number configured on the proxy. |
protocol |
protocol: str |
"http" |
The network protocol to use. Typically (http or https) |
host |
host: str |
"localhost" |
The Host of the PMS. If using on a local network, this is the internal IP address of the server hosting the PMS. If using on an external network, this is the external IP address for your network, and requires port forwarding. If using a reverse proxy, this would be the external DNS domain for your network, and requires the proxy handle port forwarding. |
full_server_url |
full_server_url: str |
"http://localhost:32400" |
The full manual URL to access the PMS |
Example
from plex_api_client import PlexAPI
from plex_api_client.models import components
with PlexAPI(
server_idx=0,
identifier="0123456789abcdef0123456789abcdef",
ip_description="1-2-3-4",
port="32400",
accepts=components.Accepts.APPLICATION_XML,
client_identifier="abc123",
product="Plex for Roku",
version="2.4.1",
platform="Roku",
platform_version="4.3 build 1057",
device="Roku 3",
model="4200X",
device_vendor="Roku",
device_name="Living Room TV",
marketplace="googlePlay",
token="<YOUR_API_KEY_HERE>",
) as plex_api:
res = plex_api.general.get_server_info(request={})
assert res.media_container_with_directory is not None
# Handle response
print(res.media_container_with_directory)
Override Server URL Per-Client
The default server can also be overridden globally by passing a URL to the server_url: str optional parameter when initializing the SDK client instance. For example:
from plex_api_client import PlexAPI
from plex_api_client.models import components
with PlexAPI(
server_url="https://http://localhost:32400",
accepts=components.Accepts.APPLICATION_XML,
client_identifier="abc123",
product="Plex for Roku",
version="2.4.1",
platform="Roku",
platform_version="4.3 build 1057",
device="Roku 3",
model="4200X",
device_vendor="Roku",
device_name="Living Room TV",
marketplace="googlePlay",
token="<YOUR_API_KEY_HERE>",
) as plex_api:
res = plex_api.general.get_server_info(request={})
assert res.media_container_with_directory is not None
# Handle response
print(res.media_container_with_directory)
Override Server URL Per-Operation
The server URL can also be overridden on a per-operation basis, provided a server list was specified for the operation. For example:
from plex_api_client import PlexAPI
from plex_api_client.models import components
with PlexAPI(
accepts=components.Accepts.APPLICATION_XML,
client_identifier="abc123",
product="Plex for Roku",
version="2.4.1",
platform="Roku",
platform_version="4.3 build 1057",
device="Roku 3",
model="4200X",
device_vendor="Roku",
device_name="Living Room TV",
marketplace="googlePlay",
token="<YOUR_API_KEY_HERE>",
) as plex_api:
res = plex_api.authentication.get_token_details(request={}, server_url="https://plex.tv/api/v2")
assert res.user_plex_account is not None
# Handle response
print(res.user_plex_account)
Custom HTTP Client
The Python SDK makes API calls using the httpx HTTP library. In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance.
Depending on whether you are using the sync or async version of the SDK, you can pass an instance of HttpClient or AsyncHttpClient respectively, which are Protocol's ensuring that the client has the necessary methods to make API calls.
This allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of httpx.Client or httpx.AsyncClient directly.
For example, you could specify a header for every request that this sdk makes as follows:
from plex_api_client import PlexAPI
import httpx
http_client = httpx.Client(headers={"x-custom-header": "someValue"})
s = PlexAPI(client=http_client)
or you could wrap the client with your own custom logic:
from plex_api_client import PlexAPI
from plex_api_client.httpclient import AsyncHttpClient
import httpx
class CustomClient(AsyncHttpClient):
client: AsyncHttpClient
def __init__(self, client: AsyncHttpClient):
self.client = client
async def send(
self,
request: httpx.Request,
*,
stream: bool = False,
auth: Union[
httpx._types.AuthTypes, httpx._client.UseClientDefault, None
] = httpx.USE_CLIENT_DEFAULT,
follow_redirects: Union[
bool, httpx._client.UseClientDefault
] = httpx.USE_CLIENT_DEFAULT,
) -> httpx.Response:
request.headers["Client-Level-Header"] = "added by client"
return await self.client.send(
request, stream=stream, auth=auth, follow_redirects=follow_redirects
)
def build_request(
self,
method: str,
url: httpx._types.URLTypes,
*,
content: Optional[httpx._types.RequestContent] = None,
data: Optional[httpx._types.RequestData] = None,
files: Optional[httpx._types.RequestFiles] = None,
json: Optional[Any] = None,
params: Optional[httpx._types.QueryParamTypes] = None,
headers: Optional[httpx._types.HeaderTypes] = None,
cookies: Optional[httpx._types.CookieTypes] = None,
timeout: Union[
httpx._types.TimeoutTypes, httpx._client.UseClientDefault
] = httpx.USE_CLIENT_DEFAULT,
extensions: Optional[httpx._types.RequestExtensions] = None,
) -> httpx.Request:
return self.client.build_request(
method,
url,
content=content,
data=data,
files=files,
json=json,
params=params,
headers=headers,
cookies=cookies,
timeout=timeout,
extensions=extensions,
)
s = PlexAPI(async_client=CustomClient(httpx.AsyncClient()))
Authentication
Per-Client Security Schemes
This SDK supports the following security scheme globally:
| Name | Type | Scheme |
|---|---|---|
token |
apiKey | API key |
To authenticate with the API the token parameter must be set when initializing the SDK client instance. For example:
from plex_api_client import PlexAPI
from plex_api_client.models import components
with PlexAPI(
token="<YOUR_API_KEY_HERE>",
accepts=components.Accepts.APPLICATION_XML,
client_identifier="abc123",
product="Plex for Roku",
version="2.4.1",
platform="Roku",
platform_version="4.3 build 1057",
device="Roku 3",
model="4200X",
device_vendor="Roku",
device_name="Living Room TV",
marketplace="googlePlay",
) as plex_api:
res = plex_api.general.get_server_info(request={})
assert res.media_container_with_directory is not None
# Handle response
print(res.media_container_with_directory)
Resource Management
The PlexAPI class implements the context manager protocol and registers a finalizer function to close the underlying sync and async HTTPX clients it uses under the hood. This will close HTTP connections, release memory and free up other resources held by the SDK. In short-lived Python programs and notebooks that make a few SDK method calls, resource management may not be a concern. However, in longer-lived programs, it is beneficial to create a single SDK instance via a context manager and reuse it across the application.
from plex_api_client import PlexAPI
from plex_api_client.models import components
def main():
with PlexAPI(
accepts=components.Accepts.APPLICATION_XML,
client_identifier="abc123",
product="Plex for Roku",
version="2.4.1",
platform="Roku",
platform_version="4.3 build 1057",
device="Roku 3",
model="4200X",
device_vendor="Roku",
device_name="Living Room TV",
marketplace="googlePlay",
token="<YOUR_API_KEY_HERE>",
) as plex_api:
# Rest of application here...
# Or when using async:
async def amain():
async with PlexAPI(
accepts=components.Accepts.APPLICATION_XML,
client_identifier="abc123",
product="Plex for Roku",
version="2.4.1",
platform="Roku",
platform_version="4.3 build 1057",
device="Roku 3",
model="4200X",
device_vendor="Roku",
device_name="Living Room TV",
marketplace="googlePlay",
token="<YOUR_API_KEY_HERE>",
) as plex_api:
# Rest of application here...
Debugging
You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass your own logger class directly into your SDK.
from plex_api_client import PlexAPI
import logging
logging.basicConfig(level=logging.DEBUG)
s = PlexAPI(debug_logger=logging.getLogger("plex_api_client"))
Development
Maturity
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
Contributions
While we value open-source contributions to this SDK, this library is generated programmatically. Feel free to open a PR or a Github issue as a proof of concept and we'll do our best to include it in a future release!