Python Client SDK Generated by Speakeasy
Project description
plexpy
Summary
Plex Media Server: OpenAPI specification for the Plex Media Server (PMS) API and the plex.tv cloud API.
Base URLs
- PMS (local server):
http(s)://{host}:{port}— Most endpoints in this spec target the local PMS. - plex.tv v2:
https://plex.tv/api/v2— Authentication, account, and social endpoints. - plex.tv v1 (legacy):
https://plex.tv/api— Legacy XML endpoints (friends, home users, claims). - Cloud providers:
https://discover.provider.plex.tv,https://metadata.provider.plex.tv, etc.
Endpoints that target plex.tv or cloud providers declare an override servers array.
Authentication
- X-Plex-Token: Pass via the
X-Plex-Tokenheader on every request. It may also be passed as a query parameter (?X-Plex-Token=...) on all endpoints. - X-Plex-Client-Identifier: Mandatory for OAuth PIN flow (
/pins) and JWT device registration. Must be a unique, persistent identifier for the client application. - OAuth PIN Flow:
POST /pins→ user visitshttps://plex.tv/link→GET /pins/{pinId}→ obtainauthToken.
Response Formats
- PMS endpoints: Return XML by default. Send
Accept: application/jsonto receive JSON. - plex.tv v2: Returns JSON by default.
- Legacy v1 endpoints (
/pins.xml,/api/resources,/api/users/): Return XML only.
Rate Limiting
plex.tv auth endpoints (PIN creation, sign-in) enforce rate limits. Clients should implement exponential backoff and reuse tokens rather than re-authenticating on every request.
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.10"
# 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,
advanced_subtitles=components.AdvancedSubtitles.BURN,
extension=operations.Extension.MPD,
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,
subtitles=operations.StartTranscodeSessionQueryParamSubtitles.BURN,
video_resolution="1080x1080",
copyts=components.BoolInt.TRUE,
video_bitrate=12000,
video_quality=50,
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.two_hundred_application_vnd_apple_mpegurl_binary_response is not None
# Handle response
print(res.two_hundred_application_vnd_apple_mpegurl_binary_response)
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,
advanced_subtitles=components.AdvancedSubtitles.BURN,
extension=operations.Extension.MPD,
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,
subtitles=operations.StartTranscodeSessionQueryParamSubtitles.BURN,
video_resolution="1080x1080",
copyts=components.BoolInt.TRUE,
video_bitrate=12000,
video_quality=50,
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.two_hundred_application_vnd_apple_mpegurl_binary_response is not None
# Handle response
print(res.two_hundred_application_vnd_apple_mpegurl_binary_response)
asyncio.run(main())
Available Resources and Operations
Available methods
Activities
- list_activities - Get all activities
- cancel_activity - Cancel a running activity
Authentication
- register_device_jwk - Register Device JWK
- get_auth_keys - Get Auth Keys
- get_auth_nonce - Get Auth Nonce
- exchange_jwt_token - Exchange JWT Token
- get_claim_token - Get Claim Token
- get_features - Get Features
- ping - Ping the server
- create_o_auth_pin - Create OAuth PIN
- create_legacy_pin - Create Legacy PIN
- link_o_auth_pin - Link OAuth PIN
- get_server_access_tokens - Get Server Access Tokens
- get_token_details - Get Token Details
- change_password - Change Password
- post_users_sign_in_data - Get User Sign In Data
- sign_out - Sign Out
- switch_home_user - Switch Home User
- get_o_auth_pin - Get OAuth PIN Status
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
DownloadQueue
- 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
DVRs
- list_dv_rs - Get DVRs
- create_dvr - Create a DVR
- delete_dvr - Delete a single DVR
- get_dvr - Get a single DVR
- patch_dvr_settings - Update DVR Settings
- update_dvr_settings - Update DVR Settings
- get_dvr_channels - Get DVR Channels
- get_dvr_guide - Get DVR Guide
- 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_epg_guide - Get EPG Guide
- get_all_languages - Get all languages
- get_lineup - Compute the best lineup
- get_lineup_channels - Get the channels for multiple lineups
- search_epg - Search EPG
- 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
- get_websocket_notifications - Get WebSocket Notifications
General
- get_server_info - Get PMS info
- get_system_accounts - Get System Accounts
- get_user_webhooks - User Webhooks
- add_user_webhook - Add User Webhook
- get_clients - Get Clients
- get_cloud_server - Get Cloud Server
- get_system_devices - Get System Devices
- get_diagnostics - Get Diagnostics
- download_database_diagnostics - Download Database Diagnostics
- download_log_bundle - Download Log Bundle
- get_geo_ip - Get GeoIP
- get_identity - Get PMS identity
- get_ip - Get IP
- claim_server - Claim Server
- refresh_reachability - Refresh Reachability
- get_source_connection_information - Get Source Connection Information
- create_transient_token - Get Transient Tokens
- get_local_servers - Get Local Servers
- browse_filesystem - Browse Filesystem
- get_bandwidth_statistics - Get Bandwidth Statistics
- get_resource_statistics - Get Resource Statistics
- get_sync_status - Get Sync Status
- get_sync_items - Get Sync Items
- get_sync_queue - Get Sync Queue
- refresh_sync_content - Refresh Sync Content
- refresh_sync_lists - Refresh Sync Lists
- get_sync_transcode_queue - Get Sync Transcode Queue
- get_metadata_agents - Get Metadata Agents
- get_system_settings - Get System Settings
- check_for_system_updates - Check for System Updates
- get_webhooks - Get Webhooks
- add_webhook - Add Webhook
- get_plex_downloads - Get Plex Downloads
- browse_filesystem_path - Browse Filesystem Path
- get_sync_item - Get Sync Item
- get_metadata_agent_details - Get Metadata Agent Details
Hubs
- get_all_hubs - Get global hubs
- get_continue_watching - Get the continue watching hub
- get_continue_watching_items - Get Continue Watching Items
- get_home_recently_added - Get home hubs Recently Added
- 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_root_library - Get Root 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_library - Get Optimize Library
- optimize_library_post - Optimize Library
- optimize_database - Optimize the Database
- get_random_artwork - Get random artwork
- get_recently_added_global - Get Global Recently Added
- get_library_sections_fallback - Get Library Sections (Fallback)
- 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
- upload_art - Upload media art Art
- get_metadata_children - Get Metadata Children
- compute_sonic_path - Compute Sonic Path
- get_metadata_grandchildren - Get Metadata Grandchildren
- get_metadata_grandparent - Get Metadata Grandparent
- get_nearest_metadata - Get Nearest Metadata
- get_metadata_on_deck - Get Metadata On Deck
- get_metadata_parent - Get Metadata Parent
- upload_poster - Upload media art Poster
- get_metadata_reviews - Get Metadata Reviews
- 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
- 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
- get_subtitles - Get 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
- get_section_agents - Get Section Agents
- update_items - Set the fields of the filtered items
- start_analysis - Analyze a section
- get_section_artists - Get Section Artists
- autocomplete - Get autocompletions for search
- get_by_content_rating - Get By Content Rating
- get_by_decade - Get By Decade
- get_by_folder - Get By Folder
- get_by_resolution - Get By Resolution
- get_by_year - Get By Year
- get_section_clips - Get Section Clips
- get_collections - Get collections in a section
- get_common - Get common fields for items
- get_section_edit - Edit Section
- edit_library_section - Edit Section
- empty_trash - Get Empty Trash
- empty_trash_post - Empty Trash
- empty_trash_put - Empty section trash
- get_section_episodes - Get Section Episodes
- get_section_filters - Get section filters
- get_first_characters - Get list of first characters
- get_library_section_hubs - Get Section Hubs
- delete_indexes - Delete section indexes
- delete_intros - Delete section intro markers
- get_section_labels - Get Section Labels
- match_section_items - Match Section Items
- move_section - Move Section
- get_section_movies - Get Section Movies
- get_newest_for_section - Get Newest for Section
- get_on_deck_for_section - Get On Deck for Section
- optimize_section - Get Optimize Section
- optimize_section_post - Optimize Section
- get_section_photos - Get Section Photos
- get_section_playlists - Get Section Playlists
- get_section_preferences - Get section prefs
- set_section_preferences - Set section prefs
- get_recently_added_for_section - Get Recently Added for Section
- cancel_refresh - Cancel section refresh
- refresh_section - Get Refresh Section
- refresh_section_post - Refresh Section
- search_section - Search Section
- get_section_settings - Get Section Settings
- get_section_shows - Get Section Shows
- get_available_sorts - Get a section sorts
- get_section_tags - Get Section Tags
- get_section_timeline - Get Section Timeline
- unmatch_section_items - Unmatch Section Items
- get_unwatched_for_section - Get Unwatched for Section
- 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
LibraryCollections
- add_collection_items - Add items to a collection
- update_collection_item - Update an item in a collection
- move_collection_item - Reorder an item in the collection
LibraryPlaylists
- create_playlist - Create a Playlist
- upload_playlist - Upload media art
- 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
LiveTV
- get_dvr_recordings - Get DVR Recordings
- get_sessions - Get all sessions
- get_dvr_recordings_by_dvr - Get DVR Recordings by DVR
- delete_live_tv_session - Delete Live TV Session
- 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
PlayQueue
- 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
Playback
- get_progress - Get Progress
- remove_from_continue_watching - Remove From Continue Watching
- player_audio_stream - Player Audio Stream
- player_mute - Player Mute
- player_pause - Player Pause
- player_play - Player Play
- player_play_media - Player Play Media
- player_refreshplayqueue - Player Refresh Play Queue
- player_seek - Player Seek
- player_set_parameters - Player Set Parameters
- player_set_rating - Player Set Rating
- player_set_state - Player Set State
- player_set_streams - Player Set Streams
- player_set_text_stream - Player Set Text Stream
- player_set_view_offset - Player Set View Offset
- player_skip_by - Player Skip By
- player_skip_to - Player Skip To
- player_stepback - Player Step Back
- player_stepforward - Player Step Forward
- player_stop - Player Stop
- player_subtitle_stream - Player Subtitle Stream
- player_unmute - Player Unmute
- player_video_stream - Player Video Stream
- player_volume - Player Volume
- get_client_resources - Get Client Resources
- player_poll_timeline - Player Poll Timeline
Playlist
- list_playlists - List playlists
- get_playlist - Retrieve Playlist
- get_playlist_items - Retrieve Playlist Contents
Playlists
- delete_playlist_by_rating_key - Delete Playlist
Plex
- get_server_resources - Get Server Resources
Preferences
- get_all_preferences - Get all preferences
- set_preferences - Set preferences
- get_preference - Get a preferences
Provider
- add_to_watchlist - Add to Watchlist
- remove_from_watchlist - Remove from Watchlist
- search_discover - Search Discover
- get_watchlist - Get Watchlist
- 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
- get_conversion_queue - Get Conversion Queue
Transcoder
- transcode_music - Transcode Music
- transcode_image - Transcode an image
- get_transcode_sessions - Get Transcode Sessions
- 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
- get_dash_segment - Get DASH Segment
- get_hls_segment - Get HLS Segment
UltraBlur
- 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_legacy_resources - Get Legacy Resources
- get_legacy_users - Get Legacy Users
- get_friends - Get Friends
- get_home - Get home hubs
- get_home_users - Get home hubs Users
- create_home_user - Create Home User
- get_my_plex_account - Get MyPlex Account
- get_user_server - Get User Server Association
- get_server_user_features - Get Server User Features
- share_server - Share Server
- update_view_state_sync - Update View State Sync
- get_users - Get list of all connected users
- get_account_xml - Get Account (XML)
- get_account_json - Get Account (JSON)
- delete_home_user - Delete Home User
- update_home_user - Update Home User
- update_restricted_user - Update Restricted User
- get_server_details - Get Server Details
- share_server_legacy - Share Server (Legacy v1)
- remove_share - Remove Share
- update_share - Update Share
- get_user_opt_outs - Get User Opt-Outs
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
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.library.upload_art(request={
"id": 996758,
"request_body": {
"file": {
"file_name": "example.file",
"content": open("example.file", "rb"),
},
},
})
assert res.success_response is not None
# Handle response
print(res.success_response)
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.object is not None
# Handle response
print(res.object)
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.object is not None
# Handle response
print(res.object)
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.general.get_server_info(request={})
assert res.object is not None
# Handle response
print(res.object)
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.Error):
print(e.data.errors) # Optional[List[errors.Errors]]
Error Classes
Primary error:
PlexAPIError: The base class for HTTP error responses.
Less common errors (8)
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:
Error: Unauthorized. Status code401. Applicable to 276 of 404 methods.*Unauthorized: Unauthorized - Returned if the X-Plex-Token is missing from the header or query. Status code401. Applicable to 4 of 404 methods.*BadRequest: Bad Request - A parameter was not specified, or was specified incorrectly. Status code400. Applicable to 3 of 404 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} |
hostportprotocol |
|
| 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. |
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. |
protocol |
protocol: str |
"http" |
The network protocol to use. Typically (http or https) |
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.object is not None
# Handle response
print(res.object)
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.object is not None
# Handle response
print(res.object)
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
with PlexAPI(
token="<YOUR_API_KEY_HERE>",
) as plex_api:
res = plex_api.general.get_user_webhooks(server_url="https://plex.tv/api/v2")
assert res.webhook_payload is not None
# Handle response
print(res.webhook_payload)
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.object is not None
# Handle response
print(res.object)
Per-Operation Security Schemes
Some operations in this SDK require the security scheme to be specified at the request level. For 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",
) as plex_api:
res = plex_api.authentication.create_o_auth_pin(security=operations.CreateOAuthPinSecurity(
client_identifier="<YOUR_API_KEY_HERE>",
), request={})
assert res.object is not None
# Handle response
print(res.object)
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!
SDK Created by Speakeasy
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file plex_api_client-0.35.0.tar.gz.
File metadata
- Download URL: plex_api_client-0.35.0.tar.gz
- Upload date:
- Size: 462.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.2.1 CPython/3.10.20 Linux/6.8.0-1062-azure
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3f899a50573114e15792fbefe7e23e5c884ac71aaf73a95f401eda8cbdb38b55
|
|
| MD5 |
f87ea9e5934aa45735da59216b38ef15
|
|
| BLAKE2b-256 |
56f4a00a6cf321081c833f6562b1dca7f139e4db4225101ff6a4591b70bad15e
|
File details
Details for the file plex_api_client-0.35.0-py3-none-any.whl.
File metadata
- Download URL: plex_api_client-0.35.0-py3-none-any.whl
- Upload date:
- Size: 1.1 MB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.2.1 CPython/3.10.20 Linux/6.8.0-1062-azure
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
959ee45e0fd9078d0e39c0e9de3dffd7022b6a29ef1af51f931635712d887540
|
|
| MD5 |
3723dadae4cab41a0d8d64f54eb9d089
|
|
| BLAKE2b-256 |
f726aab26b04199601a3ccb99b0e3a01513d3d171d5763048e8697c201a93f2c
|