Skip to content

Repository files navigation

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-Token header 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 visits https://plex.tv/linkGET /pins/{pinId} → obtain authToken.

Response Formats

  • PMS endpoints: Return XML by default. Send Accept: application/json to 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",# ]# ///fromplex_api_clientimportPlexAPIsdk=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 Examplefromplex_api_clientimportPlexAPIfromplex_api_client.modelsimportcomponents, operationswithPlexAPI(
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>",
) asplex_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",
))
assertres.two_hundred_application_vnd_apple_mpegurl_binary_responseisnotNone# Handle responseprint(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 Exampleimportasynciofromplex_api_clientimportPlexAPIfromplex_api_client.modelsimportcomponents, operationsasyncdefmain():
asyncwithPlexAPI(
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>",
) asplex_api:
res=awaitplex_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",
))
assertres.two_hundred_application_vnd_apple_mpegurl_binary_responseisnotNone# Handle responseprint(res.two_hundred_application_vnd_apple_mpegurl_binary_response)
asyncio.run(main())

Available Resources and Operations

Available methods

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.

fromplex_api_clientimportPlexAPIfromplex_api_client.modelsimportcomponentswithPlexAPI(
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>",
) asplex_api:
res=plex_api.library.upload_art(request={
"id": 996758,
"request_body": {
"file": {
"file_name": "example.file",
"content": open("example.file", "rb"),
},
},
})
assertres.success_responseisnotNone# Handle responseprint(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:

fromplex_api_clientimportPlexAPIfromplex_api_client.modelsimportcomponentsfromplex_api_client.utilsimportBackoffStrategy, RetryConfigwithPlexAPI(
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>",
) asplex_api:
res=plex_api.general.get_server_info(request={},
RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False))
assertres.objectisnotNone# Handle responseprint(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:

fromplex_api_clientimportPlexAPIfromplex_api_client.modelsimportcomponentsfromplex_api_client.utilsimportBackoffStrategy, RetryConfigwithPlexAPI(
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>",
) asplex_api:
res=plex_api.general.get_server_info(request={})
assertres.objectisnotNone# Handle responseprint(res.object)

Error Handling

PlexAPIError is the base class for all HTTP error responses. It has the following properties:

PropertyTypeDescription
err.messagestrError message
err.status_codeintHTTP response status code eg 404
err.headershttpx.HeadersHTTP response headers
err.bodystrHTTP body. Can be empty string if no body is returned.
err.raw_responsehttpx.ResponseRaw HTTP response
err.dataOptional. Some errors may contain structured data. See Error Classes.

Example

fromplex_api_clientimportPlexAPIfromplex_api_client.modelsimportcomponents, errorswithPlexAPI(
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>",
) asplex_api:
res=Nonetry:
res=plex_api.general.get_server_info(request={})
assertres.objectisnotNone# Handle responseprint(res.object)
excepterrors.PlexAPIErrorase:
# The base class for HTTP error responsesprint(e.message)
print(e.status_code)
print(e.body)
print(e.headers)
print(e.raw_response)
# Depending on the method different errors may be thrownifisinstance(e, errors.Error):
print(e.data.errors) # Optional[List[errors.Errors]]

Error Classes

Primary error:

Less common errors (8)

Network errors:

Inherit from PlexAPIError:

  • Error: Unauthorized. Status code 401. Applicable to 277 of 405 methods.*
  • Unauthorized: Unauthorized - Returned if the X-Plex-Token is missing from the header or query. Status code 401. Applicable to 4 of 405 methods.*
  • BadRequest: Bad Request - A parameter was not specified, or was specified incorrectly. Status code 400. Applicable to 3 of 405 methods.*
  • ResponseValidationError: Type mismatch between the response data and the expected Pydantic model. Provides access to the Pydantic validation error via the cause attribute.

* 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:

#ServerVariablesDescription
0https://{IP-description}.{identifier}.plex.direct:{port}identifier
IP-description
port
1{protocol}://{host}:{port}host
port
protocol
2https://{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:

VariableParameterDefaultDescription
identifieridentifier: str"0123456789abcdef0123456789abcdef"The unique identifier of this particular PMS
IP-descriptionip_description: str"1-2-3-4"A - separated string of the IPv4 or IPv6 address components
portport: 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.
hosthost: 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.
protocolprotocol: str"http"The network protocol to use. Typically (http or https)
full_server_urlfull_server_url: str"http://localhost:32400"The full manual URL to access the PMS

Example

fromplex_api_clientimportPlexAPIfromplex_api_client.modelsimportcomponentswithPlexAPI(
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>",
) asplex_api:
res=plex_api.general.get_server_info(request={})
assertres.objectisnotNone# Handle responseprint(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:

fromplex_api_clientimportPlexAPIfromplex_api_client.modelsimportcomponentswithPlexAPI(
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>",
) asplex_api:
res=plex_api.general.get_server_info(request={})
assertres.objectisnotNone# Handle responseprint(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:

fromplex_api_clientimportPlexAPIwithPlexAPI(
token="<YOUR_API_KEY_HERE>",
) asplex_api:
res=plex_api.general.get_user_webhooks(server_url="https://plex.tv/api/v2")
assertres.webhook_payloadisnotNone# Handle responseprint(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:

fromplex_api_clientimportPlexAPIimporthttpxhttp_client=httpx.Client(headers={"x-custom-header": "someValue"})
s=PlexAPI(client=http_client)

or you could wrap the client with your own custom logic:

fromplex_api_clientimportPlexAPIfromplex_api_client.httpclientimportAsyncHttpClientimporthttpxclassCustomClient(AsyncHttpClient):
client: AsyncHttpClientdef__init__(self, client: AsyncHttpClient):
self.client=clientasyncdefsend(
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"returnawaitself.client.send(
request, stream=stream, auth=auth, follow_redirects=follow_redirects
)
defbuild_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:
returnself.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()))

httpx2 (Pydantic's httpx fork)

httpx2 is Pydantic's maintained fork of httpx. To run this SDK on httpx2, call alias_httpx() at your program's entry point, before importing the SDK, so every import httpx — including the ones inside the SDK — resolves to httpx2:

importhttpx2httpx2.alias_httpx()
fromplex_api_clientimportPlexAPIs=PlexAPI()

An SDK can also be generated against httpx2 directly, so it depends on the fork instead of httpx, by setting python.httpClientLibrary: httpx2 in gen.yaml.

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

NameTypeScheme
tokenapiKeyAPI key

To authenticate with the API the token parameter must be set when initializing the SDK client instance. For example:

fromplex_api_clientimportPlexAPIfromplex_api_client.modelsimportcomponentswithPlexAPI(
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",
) asplex_api:
res=plex_api.general.get_server_info(request={})
assertres.objectisnotNone# Handle responseprint(res.object)

Per-Operation Security Schemes

Some operations in this SDK require the security scheme to be specified at the request level. For example:

fromplex_api_clientimportPlexAPIfromplex_api_client.modelsimportcomponents, operationswithPlexAPI(
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",
) asplex_api:
res=plex_api.authentication.create_o_auth_pin(security=operations.CreateOAuthPinSecurity(
client_identifier="<YOUR_API_KEY_HERE>",
), request={})
assertres.objectisnotNone# Handle responseprint(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.

fromplex_api_clientimportPlexAPIfromplex_api_client.modelsimportcomponentsdefmain():
withPlexAPI(
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>",
) asplex_api:
# Rest of application here...# Or when using async:asyncdefamain():
asyncwithPlexAPI(
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>",
) asplex_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.

fromplex_api_clientimportPlexAPIimportlogginglogging.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

About

An open source Plex Media Server python SDK

Resources

Contributing

Stars

28 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages