Plex Media Server: OpenAPI specification for the Plex Media Server (PMS) API and the plex.tv cloud API.
- 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.
- X-Plex-Token: Pass via the
X-Plex-Tokenheader on every request. It may also be passed as a query parameter (?X-Plex-Token=...) on all endpoints. - X-Plex-Client-Identifier: Mandatory for OAuth PIN flow (
/pins) and JWT device registration. Must be a unique, persistent identifier for the client application. - OAuth PIN Flow:
POST /pins→ user visitshttps://plex.tv/link→GET /pins/{pinId}→ obtainauthToken.
- PMS endpoints: Return XML by default. Send
Accept: application/jsonto receive JSON. - plex.tv v2: Returns JSON by default.
- Legacy v1 endpoints (
/pins.xml,/api/resources,/api/users/): Return XML only.
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.
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>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.signingOn Windows:
gradlew.bat publishToMavenLocal -Pskip.signingpackage 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
}
}
}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());
}
});
}
}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 methods
- listActivities - Get all activities
- cancelActivity - Cancel a running activity
- registerDeviceJWK - Register Device JWK
- getAuthKeys - Get Auth Keys
- getAuthNonce - Get Auth Nonce
- exchangeJWTToken - Exchange JWT Token
- getClaimToken - Get Claim Token
- getFeatures - Get Features
- ping - Ping the server
- createOAuthPin - Create OAuth PIN
- createLegacyPin - Create Legacy PIN
- linkOAuthPin - Link OAuth PIN
- getServerAccessTokens - Get Server Access Tokens
- getTokenDetails - Get Token Details
- changePassword - Change Password
- postUsersSignInData - Get User Sign In Data
- signOut - Sign Out
- switchHomeUser - Switch Home User
- getOAuthPin - Get OAuth PIN Status
- stopTasks - Stop all Butler tasks
- getTasks - Get all Butler tasks
- startTasks - Start all Butler tasks
- stopTask - Stop a single Butler task
- startTask - Start a single Butler task
- createCollection - Create collection
- getCollectionItems - Get items in a collection
- getMetadataItem - Get a metadata item
- getAlbums - Set section albums
- listContent - Get items in the section
- getAllLeaves - Set section leaves
- getArts - Set section artwork
- getCategories - Set section categories
- getCluster - Set section clusters
- getSonicPath - Similar tracks to transition from one to another
- getFolders - Get all folder locations
- listMoments - Set section moments
- getSonicallySimilar - The nearest audio tracks
- getCollectionImage - Get a collection's image
- getAvailableGrabbers - Get available grabbers
- listDevices - Get all devices
- addDevice - Add a device
- discoverDevices - Tell grabbers to discover devices
- removeDevice - Remove a device
- getDeviceDetails - Get device details
- modifyDevice - Enable or disable a device
- setChannelmap - Set a device's channel mapping
- getDevicesChannels - Get a device's channels
- setDevicePreferences - Set device preferences
- stopScan - Tell a device to stop scanning for channels
- scan - Tell a device to scan for channels
- getThumb - Get device thumb
- createDownloadQueue - Create download queue
- getDownloadQueue - Get a download queue
- addDownloadQueueItems - Add to download queue
- listDownloadQueueItems - Get download queue items
- getItemDecision - Grab download queue item decision
- getDownloadQueueMedia - Grab download queue media
- removeDownloadQueueItems - Delete download queue items
- getDownloadQueueItems - Get download queue items
- restartProcessingDownloadQueueItems - Restart processing of items from the decision
- listDVRs - Get DVRs
- createDVR - Create a DVR
- deleteDVR - Delete a single DVR
- getDVR - Get a single DVR
- patchDVRSettings - Update DVR Settings
- updateDVRSettings - Update DVR Settings
- getDVRChannels - Get DVR Channels
- getDVRGuide - Get DVR Guide
- deleteLineup - Delete a DVR Lineup
- addLineup - Add a DVR Lineup
- setDVRPreferences - Set DVR preferences
- stopDVRReload - Tell a DVR to stop reloading program guide
- reloadGuide - Tell a DVR to reload program guide
- tuneChannel - Tune a channel on a DVR
- removeDeviceFromDVR - Remove a device from an existing DVR
- addDeviceToDVR - Add a device to an existing DVR
- computeChannelMap - Compute the best channel map
- getChannels - Get channels for a lineup
- getCountries - Get all countries
- getEPGGuide - Get EPG Guide
- getAllLanguages - Get all languages
- getLineup - Compute the best lineup
- getLineupChannels - Get the channels for multiple lineups
- searchEPG - Search EPG
- getCountriesLineups - Get lineups for a country via postal code
- getCountryRegions - Get regions for a country
- listLineups - Get lineups for a region
- getNotifications - Connect to Eventsource
- connectWebSocket - Connect to WebSocket
- getWebsocketNotifications - Get WebSocket Notifications
- getServerInfo - Get PMS info
- getSystemAccounts - Get System Accounts
- getUserWebhooks - User Webhooks
- addUserWebhook - Add User Webhook
- getClients - Get Clients
- getCloudServer - Get Cloud Server
- getSystemDevices - Get System Devices
- getDiagnostics - Get Diagnostics
- downloadDatabaseDiagnostics - Download Database Diagnostics
- downloadLogBundle - Download Log Bundle
- getGeoIP - Get GeoIP
- getIdentity - Get PMS identity
- getIP - Get IP
- claimServer - Claim Server
- refreshReachability - Refresh Reachability
- getSourceConnectionInformation - Get Source Connection Information
- createTransientToken - Get Transient Tokens
- getLocalServers - Get Local Servers
- browseFilesystem - Browse Filesystem
- getBandwidthStatistics - Get Bandwidth Statistics
- getResourceStatistics - Get Resource Statistics
- getSyncStatus - Get Sync Status
- getSyncItems - Get Sync Items
- getSyncQueue - Get Sync Queue
- refreshSyncContent - Refresh Sync Content
- refreshSyncLists - Refresh Sync Lists
- getSyncTranscodeQueue - Get Sync Transcode Queue
- getMetadataAgents - Get Metadata Agents
- getSystemSettings - Get System Settings
- checkForSystemUpdates - Check for System Updates
- getWebhooks - Get Webhooks
- addWebhook - Add Webhook
- getPlexDownloads - Get Plex Downloads
- browseFilesystemPath - Browse Filesystem Path
- getSyncItem - Get Sync Item
- getMetadataAgentDetails - Get Metadata Agent Details
- getAllHubs - Get global hubs
- getContinueWatching - Get the continue watching hub
- getContinueWatchingItems - Get Continue Watching Items
- getHomeRecentlyAdded - Get home hubs Recently Added
- getHubItems - Get a hub's items
- getPromotedHubs - Get the hubs which are promoted
- getMetadataHubs - Get hubs for section by metadata item
- getPostplayHubs - Get postplay hubs
- getRelatedHubs - Get related hubs
- getSectionHubs - Get section hubs
- resetSectionDefaults - Reset hubs to defaults
- listHubs - Get hubs
- createCustomHub - Create a custom hub
- moveHub - Move Hub
- deleteCustomHub - Delete a custom hub
- updateHubVisibility - Change hub visibility
- getRootLibrary - Get Root Library
- getLibraryItems - Get all items in library
- deleteCaches - Delete library caches
- cleanBundles - Clean bundles
- ingestTransientItem - Ingest a transient item
- getLibraryMatches - Get library matches
- optimizeLibrary - Get Optimize Library
- optimizeLibraryPost - Optimize Library
- optimizeDatabase - Optimize the Database
- getRandomArtwork - Get random artwork
- getRecentlyAddedGlobal - Get Global Recently Added
- getLibrarySectionsFallback - Get Library Sections (Fallback)
- getSections - Get library sections (main Media Provider Only)
- addSection - Add a library section
- stopAllRefreshes - Stop refresh
- getSectionsPrefs - Get section prefs
- refreshSectionsMetadata - Refresh all sections
- getTags - Get all library tags of a type
- uploadArt - Upload media art Art
- getMetadataChildren - Get Metadata Children
- computeSonicPath - Compute Sonic Path
- getMetadataGrandchildren - Get Metadata Grandchildren
- getMetadataGrandparent - Get Metadata Grandparent
- getNearestMetadata - Get Nearest Metadata
- getMetadataOnDeck - Get Metadata On Deck
- getMetadataParent - Get Metadata Parent
- uploadPoster - Upload media art Poster
- getMetadataReviews - Get Metadata Reviews
- deleteMetadataItem - Delete a metadata item
- editMetadataItem - Edit a metadata item
- detectAds - Ad-detect an item
- getAllItemLeaves - Get the leaves of an item
- analyzeMetadata - Analyze an item
- generateThumbs - Generate thumbs of chapters for an item
- detectCredits - Credit detect a metadata item
- getExtras - Get an item's extras
- addExtras - Add to an item's extras
- getFile - Get a file from a metadata or media bundle
- startBifGeneration - Start BIF generation of an item
- detectIntros - Intro detect an item
- createMarker - Create a marker
- matchItem - Match a metadata item
- listMatches - Get metadata matches for an item
- mergeItems - Merge a metadata item
- setItemPreferences - Set metadata preferences
- refreshItemsMetadata - Refresh a metadata item
- getRelatedItems - Get related items
- listSimilar - Get similar items
- splitItem - Split a metadata item
- getSubtitles - Get subtitles
- getItemTree - Get metadata items as a tree
- unmatch - Unmatch a metadata item
- listTopUsers - Get metadata top users
- detectVoiceActivity - Detect voice activity
- getAugmentationStatus - Get augmentation status
- setStreamSelection - Set stream selection
- getPerson - Get person details
- listPersonMedia - Get media for a person
- deleteLibrarySection - Delete a library section
- getLibraryDetails - Get a library section by id
- editSection - Edit a library section
- getSectionAgents - Get Section Agents
- updateItems - Set the fields of the filtered items
- startAnalysis - Analyze a section
- getSectionArtists - Get Section Artists
- autocomplete - Get autocompletions for search
- getByContentRating - Get By Content Rating
- getByDecade - Get By Decade
- getByFolder - Get By Folder
- getByResolution - Get By Resolution
- getByYear - Get By Year
- getSectionClips - Get Section Clips
- getCollections - Get collections in a section
- getCommon - Get common fields for items
- getSectionEdit - Edit Section
- editLibrarySection - Edit Section
- emptyTrash - Get Empty Trash
- emptyTrashPost - Empty Trash
- emptyTrashPut - Empty section trash
- getSectionEpisodes - Get Section Episodes
- getSectionFilters - Get section filters
- getFirstCharacters - Get list of first characters
- getLibrarySectionHubs - Get Section Hubs
- deleteIndexes - Delete section indexes
- deleteIntros - Delete section intro markers
- getSectionLabels - Get Section Labels
- matchSectionItems - Match Section Items
- moveSection - Move Section
- getSectionMovies - Get Section Movies
- getNewestForSection - Get Newest for Section
- getOnDeckForSection - Get On Deck for Section
- optimizeSection - Get Optimize Section
- optimizeSectionPost - Optimize Section
- getSectionPhotos - Get Section Photos
- getSectionPlaylists - Get Section Playlists
- getSectionPreferences - Get section prefs
- setSectionPreferences - Set section prefs
- getRecentlyAddedForSection - Get Recently Added for Section
- cancelRefresh - Cancel section refresh
- refreshSection - Get Refresh Section
- refreshSectionPost - Refresh Section
- searchSection - Search Section
- getSectionSettings - Get Section Settings
- getSectionShows - Get Section Shows
- getAvailableSorts - Get a section sorts
- getSectionTags - Get Section Tags
- getSectionTimeline - Get Section Timeline
- unmatchSectionItems - Unmatch Section Items
- getUnwatchedForSection - Get Unwatched for Section
- getStreamLevels - Get loudness about a stream in json
- getStreamLoudness - Get loudness about a stream
- getChapterImage - Get a chapter image
- setItemArtwork - Set an item's artwork, theme, etc
- updateItemArtwork - Set an item's artwork, theme, etc
- deleteMarker - Delete a marker
- editMarker - Edit a marker
- deleteMediaItem - Delete a media item
- getPartIndex - Get BIF index for a part
- deleteCollection - Delete a collection
- getSectionImage - Get a section composite image
- deleteStream - Delete a stream
- getStream - Get a stream
- setStreamOffset - Set a stream offset
- getItemArtwork - Get an item's artwork, theme, etc
- getMediaPart - Get a media part
- getImageFromBif - Get an image from part BIF
- addCollectionItems - Add items to a collection
- updateCollectionItem - Update an item in a collection
- moveCollectionItem - Reorder an item in the collection
- createPlaylist - Create a Playlist
- uploadPlaylist - Upload media art
- deletePlaylist - Delete a Playlist
- updatePlaylist - Editing a Playlist
- getPlaylistGenerators - Get a playlist's generators
- clearPlaylistItems - Clearing a playlist
- addPlaylistItems - Adding to a Playlist
- deletePlaylistItem - Delete a Generator
- getPlaylistGenerator - Get a playlist generator
- getPlaylistGeneratorItems - Get a playlist generator's items
- movePlaylistItem - Moving items in a playlist
- refreshPlaylist - Reprocess a generator
- getDVRRecordings - Get DVR Recordings
- getSessions - Get all sessions
- getDVRRecordingsByDVR - Get DVR Recordings by DVR
- deleteLiveTVSession - Delete Live TV Session
- getLiveTVSession - Get a single session
- getSessionPlaylistIndex - Get a session playlist index
- getSessionSegment - Get a single session segment
- 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
- createPlayQueue - Create a play queue
- getPlayQueue - Retrieve a play queue
- addToPlayQueue - Add a generator or playlist to a play queue
- clearPlayQueue - Clear a play queue
- resetPlayQueue - Reset a play queue
- shuffle - Shuffle a play queue
- unshuffle - Unshuffle a play queue
- deletePlayQueueItem - Delete an item from a play queue
- movePlayQueueItem - Move an item in a play queue
- getProgress - Get Progress
- removeFromContinueWatching - Remove From Continue Watching
- playerAudioStream - Player Audio Stream
- playerMute - Player Mute
- playerPause - Player Pause
- playerPlay - Player Play
- playerPlayMedia - Player Play Media
- playerRefreshplayqueue - Player Refresh Play Queue
- playerSeek - Player Seek
- playerSetParameters - Player Set Parameters
- playerSetRating - Player Set Rating
- playerSetState - Player Set State
- playerSetStreams - Player Set Streams
- playerSetTextStream - Player Set Text Stream
- playerSetViewOffset - Player Set View Offset
- playerSkipBy - Player Skip By
- playerSkipTo - Player Skip To
- playerStepback - Player Step Back
- playerStepforward - Player Step Forward
- playerStop - Player Stop
- playerSubtitleStream - Player Subtitle Stream
- playerUnmute - Player Unmute
- playerVideoStream - Player Video Stream
- playerVolume - Player Volume
- getClientResources - Get Client Resources
- playerPollTimeline - Player Poll Timeline
- listPlaylists - List playlists
- getPlaylist - Retrieve Playlist
- getPlaylistItems - Retrieve Playlist Contents
- deletePlaylistByRatingKey - Delete Playlist
- getServerResources - Get Server Resources
- getAllPreferences - Get all preferences
- setPreferences - Set preferences
- getPreference - Get a preferences
- addToWatchlist - Add to Watchlist
- removeFromWatchlist - Remove from Watchlist
- searchDiscover - Search Discover
- getWatchlist - Get Watchlist
- listProviders - Get the list of available media providers
- addProvider - Add a media provider
- refreshProviders - Refresh media providers
- deleteMediaProvider - Delete a media provider
- setRating - Rate an item
- searchHubs - Search Hub
- voiceSearchHubs - Voice Search Hub
- listSessions - List Sessions
- getBackgroundTasks - Get background tasks
- listPlaybackHistory - List Playback History
- terminateSession - Terminate a session
- deleteHistory - Delete Single History Item
- getHistoryItem - Get Single History Item
- getAllSubscriptions - Get all subscriptions
- createSubscription - Create a subscription
- processSubscriptions - Process all subscriptions
- getScheduledRecordings - Get all scheduled recordings
- getTemplate - Get the subscription template
- cancelGrab - Cancel an existing grab
- deleteSubscription - Delete a subscription
- getSubscription - Get a single subscription
- editSubscriptionPreferences - Edit a subscription
- reorderSubscription - Re-order a subscription
- markPlayed - Mark an item as played
- report - Report media timeline
- unscrobble - Mark an item as unplayed
- getConversionQueue - Get Conversion Queue
- transcodeMusic - Transcode Music
- transcodeImage - Transcode an image
- getTranscodeSessions - Get Transcode Sessions
- makeDecision - Make a decision on media playback
- triggerFallback - Manually trigger a transcoder fallback
- transcodeSubtitles - Transcode subtitles
- startTranscodeSession - Start A Transcoding Session
- getDASHSegment - Get DASH Segment
- getHLSSegment - Get HLS Segment
- applyUpdates - Applying updates
- checkUpdates - Checking for updates
- getUpdatesStatus - Querying status of updates
- getLegacyResources - Get Legacy Resources
- getLegacyUsers - Get Legacy Users
- getFriends - Get Friends
- getHome - Get home hubs
- getHomeUsers - Get home hubs Users
- createHomeUser - Create Home User
- getMyPlexAccount - Get MyPlex Account
- getUserServer - Get User Server Association
- getServerUserFeatures - Get Server User Features
- shareServer - Share Server
- updateViewStateSync - Update View State Sync
- getUsers - Get list of all connected users
- getAccountXML - Get Account (XML)
- getAccountJSON - Get Account (JSON)
- deleteHomeUser - Delete Home User
- updateHomeUser - Update Home User
- updateRestrictedUser - Update Restricted User
- getServerDetails - Get Server Details
- shareServerLegacy - Share Server (Legacy v1)
- removeShare - Remove Share
- updateShare - Update Share
- getUserOptOuts - Get User Opt-Outs
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());
}
}
}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) |
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)
} }
}Primary error:
PlexAPIError: The base class for HTTP error responses.
Less common errors (9)
Network errors:
java.io.IOException(always wrapped byjava.io.UncheckedIOException). Commonly encountered subclasses ofIOExceptionincludejava.net.ConnectException,java.net.SocketTimeoutException,EOFException(there are many more subclasses in the JDK platform).
Inherit from PlexAPIError:
dev.plexapi.sdk.models.errors.Error: Unauthorized. Status code401. Applicable to 276 of 403 methods.*dev.plexapi.sdk.models.errors.Unauthorized: Unauthorized - Returned if the X-Plex-Token is missing from the header or query. Status code401. Applicable to 4 of 403 methods.*dev.plexapi.sdk.models.errors.BadRequest: Bad Request - A parameter was not specified, or was specified incorrectly. Status code400. Applicable to 3 of 403 methods.*
* Check the method documentation to see if the error is applicable.
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} |
identifierIP-descriptionport |
|
| 1 | {protocol}://{host}:{port} |
hostportprotocol |
|
| 2 | https://{full_server_url} |
full_server_url |
If the selected server has variables, you may override its default values 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 |
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());
}
}
}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());
}
}
}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());
}
}
}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()andcallAsPublisherUnwrapped() - 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
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());
}
}
}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());
}
}
}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();
}
}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.
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);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. 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.