Skip to content

LukasParke/plexcsharp

Repository files navigation

Plex-API

SDK Installation

NuGet

To add the NuGet package to a .NET project:

dotnet add package LukeHagar.PlexAPI.SDK

Locally

To add a reference to a local instance of the SDK in a .NET project:

dotnet add reference LukeHagar/PlexAPI/SDK/LukeHagar.PlexAPI.SDK.csproj

SDK Example Usage

Example

using LukeHagar.PlexAPI.SDK;
using LukeHagar.PlexAPI.SDK.Models.Components;
using LukeHagar.PlexAPI.SDK.Models.Requests;

var sdk = new PlexAPI(
    accepts: LukeHagar.PlexAPI.SDK.Models.Components.Accepts.ApplicationXml,
    clientIdentifier: "abc123",
    product: "Plex for Roku",
    version: "2.4.1",
    platform: "Roku",
    platformVersion: "4.3 build 1057",
    device: "Roku 3",
    model: "4200X",
    deviceVendor: "Roku",
    deviceName: "Living Room TV",
    marketplace: "googlePlay",
    token: "<YOUR_API_KEY_HERE>"
);

StartTranscodeSessionRequest req = new StartTranscodeSessionRequest() {
    TranscodeType = TranscodeType.Music,
    AdvancedSubtitles = LukeHagar.PlexAPI.SDK.Models.Components.AdvancedSubtitles.Burn,
    Extension = Extension.Mpd,
    AudioBoost = 50,
    AudioChannelCount = 5,
    AutoAdjustQuality = BoolInt.True,
    AutoAdjustSubtitle = BoolInt.True,
    DirectPlay = BoolInt.True,
    DirectStream = BoolInt.True,
    DirectStreamAudio = BoolInt.True,
    DisableResolutionRotation = BoolInt.True,
    HasMDE = BoolInt.True,
    Location = StartTranscodeSessionQueryParamLocation.Wan,
    MediaBufferSize = 102400,
    MediaIndex = 0,
    MusicBitrate = 5000,
    Offset = 90.5D,
    PartIndex = 0,
    Path = "/library/metadata/151671",
    PeakBitrate = 12000,
    PhotoResolution = "1080x1080",
    Protocol = StartTranscodeSessionQueryParamProtocol.Dash,
    SecondsPerSegment = 5,
    SubtitleSize = 50,
    Subtitles = StartTranscodeSessionQueryParamSubtitles.Burn,
    VideoResolution = "1080x1080",
    Copyts = BoolInt.True,
    VideoBitrate = 12000,
    VideoQuality = 50,
    XPlexClientProfileExtra = "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)",
    XPlexClientProfileName = "generic",
};

var res = await sdk.Transcoder.StartTranscodeSessionAsync(req);

// handle response

Available Resources and Operations

Available methods
  • WriteLog - Logging a multi-line message to the Plex Media Server log
  • WriteMessage - Logging a single-line message to the Plex Media Server log
  • EnablePapertrail - Enabling Papertrail

Server Selection

Select Server by Index

You can override the default server globally by passing a server index to the serverIndex: 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} identifier
IP-description
port
1 {protocol}://{host}:{port} host
port
protocol
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: string "0123456789abcdef0123456789abcdef" The unique identifier of this particular PMS
IP-description ipDescription: string "1-2-3-4" A - separated string of the IPv4 or IPv6 address components
port port: string "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: string "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: string "http" The network protocol to use. Typically (http or https)
full_server_url fullServerUrl: string "http://localhost:32400" The full manual URL to access the PMS

Example

using LukeHagar.PlexAPI.SDK;
using LukeHagar.PlexAPI.SDK.Models.Components;
using LukeHagar.PlexAPI.SDK.Models.Requests;

var sdk = new PlexAPI(
    serverIndex: 0,
    identifier: "0123456789abcdef0123456789abcdef",
    ipDescription: "1-2-3-4",
    port: "32400",
    accepts: LukeHagar.PlexAPI.SDK.Models.Components.Accepts.ApplicationXml,
    clientIdentifier: "abc123",
    product: "Plex for Roku",
    version: "2.4.1",
    platform: "Roku",
    platformVersion: "4.3 build 1057",
    device: "Roku 3",
    model: "4200X",
    deviceVendor: "Roku",
    deviceName: "Living Room TV",
    marketplace: "googlePlay",
    token: "<YOUR_API_KEY_HERE>"
);

GetServerInfoRequest req = new GetServerInfoRequest() {};

var res = await sdk.General.GetServerInfoAsync(req);

// handle response

Override Server URL Per-Client

The default server can also be overridden globally by passing a URL to the serverUrl: string optional parameter when initializing the SDK client instance. For example:

using LukeHagar.PlexAPI.SDK;
using LukeHagar.PlexAPI.SDK.Models.Components;
using LukeHagar.PlexAPI.SDK.Models.Requests;

var sdk = new PlexAPI(
    serverUrl: "https://http://localhost:32400",
    accepts: LukeHagar.PlexAPI.SDK.Models.Components.Accepts.ApplicationXml,
    clientIdentifier: "abc123",
    product: "Plex for Roku",
    version: "2.4.1",
    platform: "Roku",
    platformVersion: "4.3 build 1057",
    device: "Roku 3",
    model: "4200X",
    deviceVendor: "Roku",
    deviceName: "Living Room TV",
    marketplace: "googlePlay",
    token: "<YOUR_API_KEY_HERE>"
);

GetServerInfoRequest req = new GetServerInfoRequest() {};

var res = await sdk.General.GetServerInfoAsync(req);

// handle response

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:

using LukeHagar.PlexAPI.SDK;
using LukeHagar.PlexAPI.SDK.Models.Components;

var sdk = new PlexAPI(token: "<YOUR_API_KEY_HERE>");

var res = await sdk.General.GetUserWebhooksAsync(serverUrl: "https://plex.tv/api/v2");

// handle response

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:

using LukeHagar.PlexAPI.SDK;
using LukeHagar.PlexAPI.SDK.Models.Components;
using LukeHagar.PlexAPI.SDK.Models.Requests;

var sdk = new PlexAPI(
    token: "<YOUR_API_KEY_HERE>",
    accepts: LukeHagar.PlexAPI.SDK.Models.Components.Accepts.ApplicationXml,
    clientIdentifier: "abc123",
    product: "Plex for Roku",
    version: "2.4.1",
    platform: "Roku",
    platformVersion: "4.3 build 1057",
    device: "Roku 3",
    model: "4200X",
    deviceVendor: "Roku",
    deviceName: "Living Room TV",
    marketplace: "googlePlay"
);

GetServerInfoRequest req = new GetServerInfoRequest() {};

var res = await sdk.General.GetServerInfoAsync(req);

// handle response

Per-Operation Security Schemes

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

using LukeHagar.PlexAPI.SDK;
using LukeHagar.PlexAPI.SDK.Models.Requests;

var sdk = new PlexAPI(
    accepts: LukeHagar.PlexAPI.SDK.Models.Components.Accepts.ApplicationXml,
    clientIdentifier: "abc123",
    product: "Plex for Roku",
    version: "2.4.1",
    platform: "Roku",
    platformVersion: "4.3 build 1057",
    device: "Roku 3",
    model: "4200X",
    deviceVendor: "Roku",
    deviceName: "Living Room TV",
    marketplace: "googlePlay"
);

CreateOAuthPinRequest req = new CreateOAuthPinRequest() {};

var res = await sdk.Authentication.CreateOAuthPinAsync(
    security: new CreateOAuthPinSecurity() {
        ClientIdentifier = "<YOUR_API_KEY_HERE>",
    },
    request: req
);

// handle 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 pass a RetryConfig to the call:

using LukeHagar.PlexAPI.SDK;
using LukeHagar.PlexAPI.SDK.Models.Components;
using LukeHagar.PlexAPI.SDK.Models.Requests;

var sdk = new PlexAPI(
    accepts: LukeHagar.PlexAPI.SDK.Models.Components.Accepts.ApplicationXml,
    clientIdentifier: "abc123",
    product: "Plex for Roku",
    version: "2.4.1",
    platform: "Roku",
    platformVersion: "4.3 build 1057",
    device: "Roku 3",
    model: "4200X",
    deviceVendor: "Roku",
    deviceName: "Living Room TV",
    marketplace: "googlePlay",
    token: "<YOUR_API_KEY_HERE>"
);

GetServerInfoRequest req = new GetServerInfoRequest() {};

var res = await sdk.General.GetServerInfoAsync(
    retryConfig: new RetryConfig(
        strategy: RetryConfig.RetryStrategy.BACKOFF,
        backoff: new BackoffStrategy(
            initialIntervalMs: 1L,
            maxIntervalMs: 50L,
            maxElapsedTimeMs: 100L,
            exponent: 1.1
        ),
        retryConnectionErrors: false
    ),
    request: req
);

// handle response

If you'd like to override the default retry strategy for all operations that support retries, you can use the RetryConfig optional parameter when intitializing the SDK:

using LukeHagar.PlexAPI.SDK;
using LukeHagar.PlexAPI.SDK.Models.Components;
using LukeHagar.PlexAPI.SDK.Models.Requests;

var sdk = new PlexAPI(
    retryConfig: new RetryConfig(
        strategy: RetryConfig.RetryStrategy.BACKOFF,
        backoff: new BackoffStrategy(
            initialIntervalMs: 1L,
            maxIntervalMs: 50L,
            maxElapsedTimeMs: 100L,
            exponent: 1.1
        ),
        retryConnectionErrors: false
    ),
    accepts: LukeHagar.PlexAPI.SDK.Models.Components.Accepts.ApplicationXml,
    clientIdentifier: "abc123",
    product: "Plex for Roku",
    version: "2.4.1",
    platform: "Roku",
    platformVersion: "4.3 build 1057",
    device: "Roku 3",
    model: "4200X",
    deviceVendor: "Roku",
    deviceName: "Living Room TV",
    marketplace: "googlePlay",
    token: "<YOUR_API_KEY_HERE>"
);

GetServerInfoRequest req = new GetServerInfoRequest() {};

var res = await sdk.General.GetServerInfoAsync(req);

// handle response

Error Handling

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

Property Type Description
Message string Error message
StatusCode int HTTP status code
Headers HttpResponseHeaders HTTP headers
ContentType string? HTTP content type
RawResponse HttpResponseMessage HTTP response object
Body string HTTP response body

Some exceptions in this SDK include an additional Payload field, which will contain deserialized custom error data when present. Possible exceptions are listed in the Error Classes section.

Example

using LukeHagar.PlexAPI.SDK;
using LukeHagar.PlexAPI.SDK.Models.Components;
using LukeHagar.PlexAPI.SDK.Models.Errors;
using LukeHagar.PlexAPI.SDK.Models.Requests;
using System.Collections.Generic;

var sdk = new PlexAPI(
    accepts: LukeHagar.PlexAPI.SDK.Models.Components.Accepts.ApplicationXml,
    clientIdentifier: "abc123",
    product: "Plex for Roku",
    version: "2.4.1",
    platform: "Roku",
    platformVersion: "4.3 build 1057",
    device: "Roku 3",
    model: "4200X",
    deviceVendor: "Roku",
    deviceName: "Living Room TV",
    marketplace: "googlePlay",
    token: "<YOUR_API_KEY_HERE>"
);

try
{
    GetServerInfoRequest req = new GetServerInfoRequest() {};

    var res = await sdk.General.GetServerInfoAsync(req);

    // handle response
}
catch (PlexAPIError ex)  // all SDK exceptions inherit from PlexAPIError
{
    // ex.ToString() provides a detailed error message
    System.Console.WriteLine(ex);

    // Base exception fields
    HttpResponseMessage rawResponse = ex.RawResponse;
    HttpResponseHeaders headers = ex.Headers;
    int statusCode = ex.StatusCode;
    string? contentType = ex.ContentType;
    var responseBody = ex.Body;

    if (ex is Error) // different exceptions may be thrown depending on the method
    {
        // Check error data fields
        ErrorPayload payload = ex.Payload;
        List<Errors> Errors = payload.Errors;
    }

    // An underlying cause may be provided
    if (ex.InnerException != null)
    {
        Exception cause = ex.InnerException;
    }
}
catch (System.Net.Http.HttpRequestException ex)
{
    // Check ex.InnerException for Network connectivity errors
}

Error Classes

Primary exception:

Less common exceptions (5)
  • System.Net.Http.HttpRequestException: Network connectivity error. For more details about the underlying cause, inspect the ex.InnerException.

  • Inheriting from PlexAPIError:

    • Error: Unauthorized. Status code 401. Applicable to 276 of 403 methods.*
    • Unauthorized: Unauthorized - Returned if the X-Plex-Token is missing from the header or query. Status code 401. Applicable to 4 of 403 methods.*
    • BadRequest: Bad Request - A parameter was not specified, or was specified incorrectly. Status code 400. Applicable to 3 of 403 methods.*
    • ResponseValidationError: Thrown when the response data could not be deserialized into the expected type.

* Refer to the relevant documentation to determine whether an exception applies to a specific operation.

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

Custom HTTP Client

The C# SDK makes API calls using an ISpeakeasyHttpClient that wraps the native HttpClient. This client provides the ability to attach hooks around the request lifecycle that can be used to modify the request or handle errors and response.

The ISpeakeasyHttpClient interface allows you to either use the default SpeakeasyHttpClient that comes with the SDK, or provide your own custom implementation with customized configuration such as custom message handlers, timeouts, connection pooling, and other HTTP client settings.

The following example shows how to create a custom HTTP client with request modification and error handling:

using LukeHagar.PlexAPI.SDK;
using LukeHagar.PlexAPI.SDK.Utils;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

// Create a custom HTTP client
public class CustomHttpClient : ISpeakeasyHttpClient
{
    private readonly ISpeakeasyHttpClient _defaultClient;

    public CustomHttpClient()
    {
        _defaultClient = new SpeakeasyHttpClient();
    }

    public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
    {
        // Add custom header and timeout
        request.Headers.Add("x-custom-header", "custom value");
        request.Headers.Add("x-request-timeout", "30");
        
        try
        {
            var response = await _defaultClient.SendAsync(request, cancellationToken);
            // Log successful response
            Console.WriteLine($"Request successful: {response.StatusCode}");
            return response;
        }
        catch (Exception error)
        {
            // Log error
            Console.WriteLine($"Request failed: {error.Message}");
            throw;
        }
    }

    public void Dispose()
    {
        _httpClient?.Dispose();
        _defaultClient?.Dispose();
    }
}

// Use the custom HTTP client with the SDK
var customHttpClient = new CustomHttpClient();
var sdk = new PlexAPI(client: customHttpClient);
You can also provide a completely custom HTTP client with your own configuration:
using LukeHagar.PlexAPI.SDK.Utils;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;

// Custom HTTP client with custom configuration
public class AdvancedHttpClient : ISpeakeasyHttpClient
{
    private readonly HttpClient _httpClient;

    public AdvancedHttpClient()
    {
        var handler = new HttpClientHandler()
        {
            MaxConnectionsPerServer = 10,
            // ServerCertificateCustomValidationCallback = customCertValidation, // Custom SSL validation if needed
        };

        _httpClient = new HttpClient(handler)
        {
            Timeout = TimeSpan.FromSeconds(30)
        };
    }

    public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
    {
        return await _httpClient.SendAsync(request, cancellationToken ?? CancellationToken.None);
    }

    public void Dispose()
    {
        _httpClient?.Dispose();
    }
}

var sdk = PlexAPI.Builder()
    .WithClient(new AdvancedHttpClient())
    .Build();
For simple debugging, you can enable request/response logging by implementing a custom client:
public class LoggingHttpClient : ISpeakeasyHttpClient
{
    private readonly ISpeakeasyHttpClient _innerClient;

    public LoggingHttpClient(ISpeakeasyHttpClient innerClient = null)
    {
        _innerClient = innerClient ?? new SpeakeasyHttpClient();
    }

    public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
    {
        // Log request
        Console.WriteLine($"Sending {request.Method} request to {request.RequestUri}");
        
        var response = await _innerClient.SendAsync(request, cancellationToken);
        
        // Log response
        Console.WriteLine($"Received {response.StatusCode} response");
        
        return response;
    }

    public void Dispose() => _innerClient?.Dispose();
}

var sdk = new PlexAPI(client: new LoggingHttpClient());

The SDK also provides built-in hook support through the SDKConfiguration.Hooks system, which automatically handles BeforeRequestAsync, AfterSuccessAsync, and AfterErrorAsync hooks for advanced request lifecycle management.

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 C# SDK

Resources

License

Contributing

Stars

17 stars

Watchers

3 watching

Forks

Packages

 
 
 

Contributors

Languages