Skip to content

Repository files navigation

plexapi

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

Getting started

JDK 11 or later is required.

The samples below show how a published SDK artifact is used:

Gradle:

implementation 'dev.plexapi:plexapi:0.23.0'

Maven:

<dependency>
    <groupId>dev.plexapi</groupId>
    <artifactId>plexapi</artifactId>
    <version>0.23.0</version>
</dependency>

How to build

After cloning the git repository to your file system you can build the SDK artifact from source to the build directory by running ./gradlew build on *nix systems or gradlew.bat on Windows systems.

If you wish to build from source and publish the SDK artifact to your local Maven repository (on your filesystem) then use the following command (after cloning the git repo locally):

On *nix:

./gradlew publishToMavenLocal -Pskip.signing

On Windows:

gradlew.bat publishToMavenLocal -Pskip.signing

SDK Example Usage

Example

package hello.world;

import dev.plexapi.sdk.PlexAPI;
import dev.plexapi.sdk.models.operations.*;
import dev.plexapi.sdk.models.shared.*;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws Exception {

        PlexAPI sdk = PlexAPI.builder()
                .accepts(Accepts.APPLICATION_XML)
                .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(System.getenv().getOrDefault("TOKEN", ""))
            .build();

        StartTranscodeSessionRequest req = StartTranscodeSessionRequest.builder()
                .transcodeType(TranscodeType.MUSIC)
                .extension(Extension.MPD)
                .advancedSubtitles(AdvancedSubtitles.BURN)
                .audioBoost(50L)
                .audioChannelCount(5L)
                .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(102400L)
                .mediaIndex(0L)
                .musicBitrate(5000L)
                .offset(90.5)
                .partIndex(0L)
                .path("/library/metadata/151671")
                .peakBitrate(12000L)
                .photoResolution("1080x1080")
                .protocol(StartTranscodeSessionQueryParamProtocol.DASH)
                .secondsPerSegment(5L)
                .subtitleSize(50L)
                .subtitles(StartTranscodeSessionQueryParamSubtitles.BURN)
                .videoResolution("1080x1080")
                .copyts(BoolInt.True)
                .videoBitrate(12000L)
                .videoQuality(50L)
                .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")
                .build();

        StartTranscodeSessionResponse res = sdk.transcoder().startTranscodeSession()
                .request(req)
                .call();

        if (res.twoHundredApplicationVndAppleMpegurlBinaryResponse().isPresent()) {
            // handle response
        }
    }
}

Asynchronous Call

An asynchronous SDK client is also available that returns a CompletableFuture<T>. See Asynchronous Support for more details on async benefits and reactive library integration.

package hello.world;

import dev.plexapi.sdk.AsyncPlexAPI;
import dev.plexapi.sdk.PlexAPI;
import dev.plexapi.sdk.models.operations.GetServerInfoRequest;
import dev.plexapi.sdk.models.operations.async.GetServerInfoResponse;
import dev.plexapi.sdk.models.shared.Accepts;
import java.util.concurrent.CompletableFuture;

public class Application {

    public static void main(String[] args) {

        AsyncPlexAPI sdk = PlexAPI.builder()
                .accepts(Accepts.APPLICATION_XML)
                .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(System.getenv().getOrDefault("TOKEN", ""))
            .build()
            .async();

        GetServerInfoRequest req = GetServerInfoRequest.builder()
                .build();

        CompletableFuture<GetServerInfoResponse> resFut = sdk.general().getServerInfo()
                .request(req)
                .call();

        resFut.thenAccept(res -> {
            if (res.object().isPresent()) {
                System.out.println(res.object().get());
            }
        });
    }
}

Union Consumption Patterns

When a response field is a union model:

  • Discriminated unions: branch on the discriminator (switch) and then narrow to the concrete type.
  • Non-discriminated unions: use generated accessors (for example string(), asLong(), simpleObject()) to determine the active variant.

For full model-specific examples (including Java 11/16/21 variants), see each union model's Supported Types section in the generated model docs.

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

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, you can provide a RetryConfig object through the retryConfig builder method:

package hello.world;

import dev.plexapi.sdk.PlexAPI;
import dev.plexapi.sdk.models.errors.Error;
import dev.plexapi.sdk.models.operations.GetServerInfoRequest;
import dev.plexapi.sdk.models.operations.GetServerInfoResponse;
import dev.plexapi.sdk.models.shared.Accepts;
import dev.plexapi.sdk.utils.BackoffStrategy;
import dev.plexapi.sdk.utils.RetryConfig;
import java.lang.Exception;
import java.util.concurrent.TimeUnit;

public class Application {

    public static void main(String[] args) throws Error, Exception {

        PlexAPI sdk = PlexAPI.builder()
                .accepts(Accepts.APPLICATION_XML)
                .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(System.getenv().getOrDefault("TOKEN", ""))
            .build();

        GetServerInfoRequest req = GetServerInfoRequest.builder()
                .build();

        GetServerInfoResponse res = sdk.general().getServerInfo()
                .request(req)
                .retryConfig(RetryConfig.builder()
                    .backoff(BackoffStrategy.builder()
                        .initialInterval(1L, TimeUnit.MILLISECONDS)
                        .maxInterval(50L, TimeUnit.MILLISECONDS)
                        .maxElapsedTime(1000L, TimeUnit.MILLISECONDS)
                        .baseFactor(1.1)
                        .jitterFactor(0.15)
                        .retryConnectError(false)
                        .build())
                    .build())
                .call();

        if (res.object().isPresent()) {
            System.out.println(res.object().get());
        }
    }
}

If you'd like to override the default retry strategy for all operations that support retries, you can provide a configuration at SDK initialization:

package hello.world;

import dev.plexapi.sdk.PlexAPI;
import dev.plexapi.sdk.models.errors.Error;
import dev.plexapi.sdk.models.operations.GetServerInfoRequest;
import dev.plexapi.sdk.models.operations.GetServerInfoResponse;
import dev.plexapi.sdk.models.shared.Accepts;
import dev.plexapi.sdk.utils.BackoffStrategy;
import dev.plexapi.sdk.utils.RetryConfig;
import java.lang.Exception;
import java.util.concurrent.TimeUnit;

public class Application {

    public static void main(String[] args) throws Error, Exception {

        PlexAPI sdk = PlexAPI.builder()
                .retryConfig(RetryConfig.builder()
                    .backoff(BackoffStrategy.builder()
                        .initialInterval(1L, TimeUnit.MILLISECONDS)
                        .maxInterval(50L, TimeUnit.MILLISECONDS)
                        .maxElapsedTime(1000L, TimeUnit.MILLISECONDS)
                        .baseFactor(1.1)
                        .jitterFactor(0.15)
                        .retryConnectError(false)
                        .build())
                    .build())
                .accepts(Accepts.APPLICATION_XML)
                .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(System.getenv().getOrDefault("TOKEN", ""))
            .build();

        GetServerInfoRequest req = GetServerInfoRequest.builder()
                .build();

        GetServerInfoResponse res = sdk.general().getServerInfo()
                .request(req)
                .call();

        if (res.object().isPresent()) {
            System.out.println(res.object().get());
        }
    }
}

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or raise an exception.

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

Method Type Description
message() String Error message
code() int HTTP response status code eg 404
headers Map<String, List<String>> HTTP response headers
body() byte[] HTTP body as a byte array. Can be empty array if no body is returned.
bodyAsString() String HTTP body as a UTF-8 string. Can be empty string if no body is returned.
rawResponse() HttpResponse<?> Raw HTTP response (body already read and not available for re-read)

Example

package hello.world;

import dev.plexapi.sdk.PlexAPI;
import dev.plexapi.sdk.models.errors.*;
import dev.plexapi.sdk.models.errors.Error;
import dev.plexapi.sdk.models.operations.GetServerInfoRequest;
import dev.plexapi.sdk.models.operations.GetServerInfoResponse;
import dev.plexapi.sdk.models.shared.Accepts;
import java.io.UncheckedIOException;
import java.lang.Exception;
import java.util.List;
import java.util.Optional;

public class Application {

    public static void main(String[] args) throws Error, Exception {

        PlexAPI sdk = PlexAPI.builder()
                .accepts(Accepts.APPLICATION_XML)
                .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(System.getenv().getOrDefault("TOKEN", ""))
            .build();
        try {

            GetServerInfoRequest req = GetServerInfoRequest.builder()
                    .build();

            GetServerInfoResponse res = sdk.general().getServerInfo()
                    .request(req)
                    .call();

            if (res.object().isPresent()) {
                System.out.println(res.object().get());
            }
        } catch (PlexAPIError ex) { // all SDK exceptions inherit from PlexAPIError

            // ex.ToString() provides a detailed error message including
            // HTTP status code, headers, and error payload (if any)
            System.out.println(ex);

            // Base exception fields
            var rawResponse = ex.rawResponse();
            var headers = ex.headers();
            var contentType = headers.first("Content-Type");
            int statusCode = ex.code();
            Optional<byte[]> responseBody = ex.body();

            // different error subclasses may be thrown 
            // depending on the service call
            if (ex instanceof Error) {
                var e = (Error) ex;
                // Check error data fields
                e.data().ifPresent(payload -> {
                      Optional<List<Errors>> errors = payload.errors();
                });
            }

            // An underlying cause may be provided. If the error payload 
            // cannot be deserialized then the deserialization exception 
            // will be set as the cause.
            if (ex.getCause() != null) {
                var cause = ex.getCause();
            }
        } catch (UncheckedIOException ex) {
            // handle IO error (connection, timeout, etc)
        }    }
}

Error Classes

Primary error:

Less common errors (9)

Network errors:

  • java.io.IOException (always wrapped by java.io.UncheckedIOException). Commonly encountered subclasses of IOException include java.net.ConnectException, java.net.SocketTimeoutException, EOFException (there are many more subclasses in the JDK platform).

Inherit from PlexAPIError:

* Check the method documentation to see if the error is applicable.

Server Selection

Select Server by Index

You can override the default server globally using the .serverIndex(int serverIdx) builder method 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 using the associated builder method(s):

Variable BuilderMethod Default Description
identifier identifier(String identifier) "0123456789abcdef0123456789abcdef" The unique identifier of this particular PMS
IP-description ipDescription(String ipDescription) "1-2-3-4" A - separated string of the IPv4 or IPv6 address components
port port(String port) "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 host) "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 protocol) "http" The network protocol to use. Typically (http or https)
full_server_url fullServerUrl(String fullServerUrl) "http://localhost:32400" The full manual URL to access the PMS

Example

package hello.world;

import dev.plexapi.sdk.PlexAPI;
import dev.plexapi.sdk.models.errors.Error;
import dev.plexapi.sdk.models.operations.GetServerInfoRequest;
import dev.plexapi.sdk.models.operations.GetServerInfoResponse;
import dev.plexapi.sdk.models.shared.Accepts;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws Error, Exception {

        PlexAPI sdk = PlexAPI.builder()
                .serverIndex(0)
                .identifier("<value>")
                .ipDescription("<value>")
                .port("14470")
                .accepts(Accepts.APPLICATION_XML)
                .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(System.getenv().getOrDefault("TOKEN", ""))
            .build();

        GetServerInfoRequest req = GetServerInfoRequest.builder()
                .build();

        GetServerInfoResponse res = sdk.general().getServerInfo()
                .request(req)
                .call();

        if (res.object().isPresent()) {
            System.out.println(res.object().get());
        }
    }
}

Override Server URL Per-Client

The default server can also be overridden globally using the .serverURL(String serverUrl) builder method when initializing the SDK client instance. For example:

package hello.world;

import dev.plexapi.sdk.PlexAPI;
import dev.plexapi.sdk.models.errors.Error;
import dev.plexapi.sdk.models.operations.GetServerInfoRequest;
import dev.plexapi.sdk.models.operations.GetServerInfoResponse;
import dev.plexapi.sdk.models.shared.Accepts;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws Error, Exception {

        PlexAPI sdk = PlexAPI.builder()
                .serverURL("https://http://localhost:32400")
                .accepts(Accepts.APPLICATION_XML)
                .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(System.getenv().getOrDefault("TOKEN", ""))
            .build();

        GetServerInfoRequest req = GetServerInfoRequest.builder()
                .build();

        GetServerInfoResponse res = sdk.general().getServerInfo()
                .request(req)
                .call();

        if (res.object().isPresent()) {
            System.out.println(res.object().get());
        }
    }
}

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:

package hello.world;

import dev.plexapi.sdk.PlexAPI;
import dev.plexapi.sdk.models.errors.Error;
import dev.plexapi.sdk.models.operations.GetUserWebhooksResponse;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws Error, Exception {

        PlexAPI sdk = PlexAPI.builder()
                .token(System.getenv().getOrDefault("TOKEN", ""))
            .build();

        GetUserWebhooksResponse res = sdk.general().getUserWebhooks()
                .serverURL("https://plex.tv/api/v2")
                .call();

        if (res.webhookPayload().isPresent()) {
            System.out.println(res.webhookPayload().get());
        }
    }
}

Asynchronous Support

The SDK provides comprehensive asynchronous support using Java's CompletableFuture<T> and Reactive Streams Publisher<T> APIs. This design makes no assumptions about your choice of reactive toolkit, allowing seamless integration with any reactive library.

Why Use Async?

Asynchronous operations provide several key benefits:

  • Non-blocking I/O: Your threads stay free for other work while operations are in flight
  • Better resource utilization: Handle more concurrent operations with fewer threads
  • Improved scalability: Build highly responsive applications that can handle thousands of concurrent requests
  • Reactive integration: Works seamlessly with reactive streams and backpressure handling
Reactive Library Integration

The SDK returns Reactive Streams Publisher<T> instances for operations dealing with streams involving multiple I/O interactions. We use Reactive Streams instead of JDK Flow API to provide broader compatibility with the reactive ecosystem, as most reactive libraries natively support Reactive Streams.

Why Reactive Streams over JDK Flow?

  • Broader ecosystem compatibility: Most reactive libraries (Project Reactor, RxJava, Akka Streams, etc.) natively support Reactive Streams
  • Industry standard: Reactive Streams is the de facto standard for reactive programming in Java
  • Better interoperability: Seamless integration without additional adapters for most use cases

Integration with Popular Libraries:

  • Project Reactor: Use Flux.from(publisher) to convert to Reactor types
  • RxJava: Use Flowable.fromPublisher(publisher) for RxJava integration
  • Akka Streams: Use Source.fromPublisher(publisher) for Akka Streams integration
  • Vert.x: Use ReadStream.fromPublisher(vertx, publisher) for Vert.x reactive streams
  • Mutiny: Use Multi.createFrom().publisher(publisher) for Quarkus Mutiny integration

For JDK Flow API Integration: If you need JDK Flow API compatibility (e.g., for Quarkus/Mutiny 2), you can use adapters:

// Convert Reactive Streams Publisher to Flow Publisher
Flow.Publisher<T> flowPublisher = FlowAdapters.toFlowPublisher(reactiveStreamsPublisher);

// Convert Flow Publisher to Reactive Streams Publisher
Publisher<T> reactiveStreamsPublisher = FlowAdapters.toPublisher(flowPublisher);

For standard single-response operations, the SDK returns CompletableFuture<T> for straightforward async execution.

Supported Operations

Async support is available for:

  • Server-sent Events: Stream real-time events with Reactive Streams Publisher<T>
  • JSONL Streaming: Process streaming JSON lines asynchronously
  • Pagination: Iterate through paginated results using callAsPublisher() and callAsPublisherUnwrapped()
  • File Uploads: Upload files asynchronously with progress tracking
  • File Downloads: Download files asynchronously with streaming support
  • Standard Operations: All regular API calls return CompletableFuture<T> for async execution

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:

package hello.world;

import dev.plexapi.sdk.PlexAPI;
import dev.plexapi.sdk.models.errors.Error;
import dev.plexapi.sdk.models.operations.GetServerInfoRequest;
import dev.plexapi.sdk.models.operations.GetServerInfoResponse;
import dev.plexapi.sdk.models.shared.Accepts;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws Error, Exception {

        PlexAPI sdk = PlexAPI.builder()
                .token(System.getenv().getOrDefault("TOKEN", ""))
                .accepts(Accepts.APPLICATION_XML)
                .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")
            .build();

        GetServerInfoRequest req = GetServerInfoRequest.builder()
                .build();

        GetServerInfoResponse res = sdk.general().getServerInfo()
                .request(req)
                .call();

        if (res.object().isPresent()) {
            System.out.println(res.object().get());
        }
    }
}

Per-Operation Security Schemes

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

package hello.world;

import dev.plexapi.sdk.PlexAPI;
import dev.plexapi.sdk.models.errors.Error;
import dev.plexapi.sdk.models.operations.*;
import dev.plexapi.sdk.models.shared.Accepts;
import java.lang.Exception;

public class Application {

    public static void main(String[] args) throws Error, Exception {

        PlexAPI sdk = PlexAPI.builder()
                .accepts(Accepts.APPLICATION_XML)
                .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")
            .build();

        CreateOAuthPinRequest req = CreateOAuthPinRequest.builder()
                .build();

        CreateOAuthPinResponse res = sdk.authentication().createOAuthPin()
                .request(req)
                .security(CreateOAuthPinSecurity.builder()
                    .clientIdentifier(System.getenv().getOrDefault("CLIENT_IDENTIFIER", ""))
                    .build())
                .call();

        if (res.object().isPresent()) {
            System.out.println(res.object().get());
        }
    }
}

Custom HTTP Client

The Java SDK makes API calls using an HTTPClient 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 HTTPClient 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 executors, SSL context, connection pools, and other HTTP client settings.

The interface provides synchronous (send) methods and asynchronous (sendAsync) methods. The sendAsync method is used to power the async SDK methods and returns a CompletableFuture<HttpResponse<Blob>> for non-blocking operations.

The following example shows how to add a custom header and handle errors:

import dev.plexapi.sdk.PlexAPI;
import dev.plexapi.sdk.utils.HTTPClient;
import dev.plexapi.sdk.utils.SpeakeasyHTTPClient;
import dev.plexapi.sdk.utils.Utils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.InputStream;
import java.time.Duration;

public class Application {
    public static void main(String[] args) {
        // Create a custom HTTP client with hooks
        HTTPClient httpClient = new HTTPClient() {
            private final HTTPClient defaultClient = new SpeakeasyHTTPClient();
            
            @Override
            public HttpResponse<InputStream> send(HttpRequest request) throws IOException, URISyntaxException, InterruptedException {
                // Add custom header and timeout using Utils.copy()
                HttpRequest modifiedRequest = Utils.copy(request)
                    .header("x-custom-header", "custom value")
                    .timeout(Duration.ofSeconds(30))
                    .build();
                    
                try {
                    HttpResponse<InputStream> response = defaultClient.send(modifiedRequest);
                    // Log successful response
                    System.out.println("Request successful: " + response.statusCode());
                    return response;
                } catch (Exception error) {
                    // Log error
                    System.err.println("Request failed: " + error.getMessage());
                    throw error;
                }
            }
        };

        PlexAPI sdk = PlexAPI.builder()
            .client(httpClient)
            .build();
    }
}
Custom HTTP Client Configuration

You can also provide a completely custom HTTP client with your own configuration:

import dev.plexapi.sdk.PlexAPI;
import dev.plexapi.sdk.utils.HTTPClient;
import dev.plexapi.sdk.utils.Blob;
import dev.plexapi.sdk.utils.ResponseWithBody;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.InputStream;
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.CompletableFuture;

public class Application {
    public static void main(String[] args) {
        // Custom HTTP client with custom configuration
        HTTPClient customHttpClient = new HTTPClient() {
            private final HttpClient client = HttpClient.newBuilder()
                .executor(Executors.newFixedThreadPool(10))
                .connectTimeout(Duration.ofSeconds(30))
                // .sslContext(customSslContext) // Add custom SSL context if needed
                .build();

            @Override
            public HttpResponse<InputStream> send(HttpRequest request) throws IOException, URISyntaxException, InterruptedException {
                return client.send(request, HttpResponse.BodyHandlers.ofInputStream());
            }

            @Override
            public CompletableFuture<HttpResponse<Blob>> sendAsync(HttpRequest request) {
                // Convert response to HttpResponse<Blob> for async operations
                return client.sendAsync(request, HttpResponse.BodyHandlers.ofPublisher())
                    .thenApply(resp -> new ResponseWithBody<>(resp, Blob::from));
            }
        };

        PlexAPI sdk = PlexAPI.builder()
            .client(customHttpClient)
            .build();
    }
}

You can also enable debug logging on the default SpeakeasyHTTPClient:

import dev.plexapi.sdk.PlexAPI;
import dev.plexapi.sdk.utils.SpeakeasyHTTPClient;

public class Application {
    public static void main(String[] args) {
        SpeakeasyHTTPClient httpClient = new SpeakeasyHTTPClient();
        httpClient.enableDebugLogging(true);

        PlexAPI sdk = PlexAPI.builder()
            .client(httpClient)
            .build();
    }
}

Debugging

Debug

You can setup your SDK to emit debug logs for SDK requests and responses.

For request and response logging (especially json bodies), call enableHTTPDebugLogging(boolean) on the SDK builder like so:

SDK.builder()
    .enableHTTPDebugLogging(true)
    .build();

Example output:

Sending request: http://localhost:35123/bearer#global GET
Request headers: {Accept=[application/json], Authorization=[******], Client-Level-Header=[added by client], Idempotency-Key=[some-key], x-speakeasy-user-agent=[speakeasy-sdk/java 0.0.1 internal 0.1.0 org.openapis.openapi]}
Received response: (GET http://localhost:35123/bearer#global) 200
Response headers: {access-control-allow-credentials=[true], access-control-allow-origin=[*], connection=[keep-alive], content-length=[50], content-type=[application/json], date=[Wed, 09 Apr 2025 01:43:29 GMT], server=[gunicorn/19.9.0]}
Response body:
{
  "authenticated": true, 
  "token": "global"
}

WARNING: This logging should only be used for temporary debugging purposes. Leaving this option on in a production system could expose credentials/secrets in logs. Authorization headers are redacted by default and there is the ability to specify redacted header names via SpeakeasyHTTPClient.setRedactedHeaders.

NOTE: This is a convenience method that calls HTTPClient.enableDebugLogging(). The SpeakeasyHTTPClient honors this setting. If you are using a custom HTTP client, it is up to the custom client to honor this setting.

Another option is to set the System property -Djdk.httpclient.HttpClient.log=all. However, this second option does not log bodies.

Jackson Configuration

The SDK ships with a pre-configured Jackson ObjectMapper accessible via JSON.getMapper(). It is set up with type modules, strict deserializers, and the feature flags needed for full SDK compatibility (including ISO-8601 OffsetDateTime serialization):

import dev.plexapi.sdk.utils.JSON;

String json = JSON.getMapper().writeValueAsString(response);

To compose with your own ObjectMapper, register the provided PlexapiJacksonModule, which bundles all the same modules and feature flags as a single plug-and-play module:

import dev.plexapi.sdk.utils.PlexapiJacksonModule;
import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper myMapper = new ObjectMapper()
    .registerModule(new PlexapiJacksonModule());

String json = myMapper.writeValueAsString(response);

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. Any manual changes added to internal files will be overwritten on the next generation. We look forward to hearing your feedback. Feel free to open a PR or an issue with 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 Java SDK

Resources

Contributing

Stars

Watchers

Forks

Releases

Packages

Used by

Contributors

Languages