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 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-clientPIP is the default package installer for Python, enabling easy installation and management of packages from PyPI via the command line.
pip install plex-api-clientPoetry 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-clientYou 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 pythonIt'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.
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.
# 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.ONE,
auto_adjust_subtitle=components.BoolInt.ONE,
direct_play=components.BoolInt.ONE,
direct_stream=components.BoolInt.ONE,
direct_stream_audio=components.BoolInt.ONE,
disable_resolution_rotation=components.BoolInt.ONE,
has_mde=components.BoolInt.ONE,
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.ONE,
auto_adjust_subtitle=components.BoolInt.ONE,
direct_play=components.BoolInt.ONE,
direct_stream=components.BoolInt.ONE,
direct_stream_audio=components.BoolInt.ONE,
disable_resolution_rotation=components.BoolInt.ONE,
has_mde=components.BoolInt.ONE,
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 methods
- list_activities - Get all activities
- cancel_activity - Cancel a running activity
- 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
- create_collection - Create collection
- 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
- 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
- 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
- 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
- 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
- get_notifications - Connect to Eventsource
- connect_web_socket - Connect to WebSocket
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- list_playlists - List playlists
- get_playlist - Retrieve Playlist
- get_playlist_items - Retrieve Playlist Contents
- get_all_preferences - Get all preferences
- set_preferences - Set preferences
- get_preference - Get a preferences
- 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
- set_rating - Rate an item
- search_hubs - Search Hub
- voice_search_hubs - Voice Search Hub
- 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
- 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
- mark_played - Mark an item as played
- report - Report media timeline
- unscrobble - Mark an item as unplayed
- 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
- get_colors - Get UltraBlur Colors
- get_image - Get UltraBlur Image
- apply_updates - Applying updates
- check_updates - Checking for updates
- get_updates_status - Querying status of updates
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)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)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 |
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.media_container_with_directory is not None
# Handle response
print(res.media_container_with_directory)
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)Primary error:
PlexAPIError: The base class for HTTP error responses.
Less common errors (5)
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:
ResponseValidationError: Type mismatch between the response data and the expected Pydantic model. Provides access to the Pydantic validation error via thecauseattribute.
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} |
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. |
server_url |
server_url_global: str |
"http://localhost:32400" |
The full manual URL to access the PMS |
from plex_api_client import PlexAPI
from plex_api_client.models import components
with PlexAPI(
server_idx=1,
protocol="<value>"
host="electric-excess.name"
port="36393"
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)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://{full_server_url}",
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)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()))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)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...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"))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.
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!