The SDK can be installed with either npm, pnpm, bun or yarn package managers.
npm add @lukehagar/plexjspnpm add @lukehagar/plexjsbun add @lukehagar/plexjsyarn add @lukehagar/plexjsimport { PlexAPI } from "@lukehagar/plexjs";
import {
Extension,
StartTranscodeSessionLocation,
StartTranscodeSessionProtocol,
} from "@lukehagar/plexjs/sdk/models/operations";
import {
Accepts,
AdvancedSubtitles,
BoolInt,
TranscodeType,
} from "@lukehagar/plexjs/sdk/models/shared";
const plexAPI = new PlexAPI({
accepts: 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",
});
async function run() {
const result = await plexAPI.transcoder.startTranscodeSession({
transcodeType: TranscodeType.Music,
extension: Extension.Mpd,
advancedSubtitles: AdvancedSubtitles.Burn,
audioBoost: 50,
audioChannelCount: 5,
autoAdjustQuality: BoolInt.One,
autoAdjustSubtitle: BoolInt.One,
directPlay: BoolInt.One,
directStream: BoolInt.One,
directStreamAudio: BoolInt.One,
disableResolutionRotation: BoolInt.One,
hasMDE: BoolInt.One,
location: StartTranscodeSessionLocation.Wan,
mediaBufferSize: 102400,
mediaIndex: 0,
musicBitrate: 5000,
offset: 90.5,
partIndex: 0,
path: "/library/metadata/151671",
peakBitrate: 12000,
photoResolution: "1080x1080",
protocol: StartTranscodeSessionProtocol.Dash,
secondsPerSegment: 5,
subtitleSize: 50,
videoBitrate: 12000,
videoQuality: 50,
videoResolution: "1080x1080",
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",
});
console.log(result);
}
run();Available methods
- listActivities - Get all activities
- cancelActivity - Cancel a running activity
- 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
- 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
- getAllLanguages - Get all languages
- getLineup - Compute the best lineup
- getLineupChannels - Get the channels for mulitple lineups
- 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
- getServerInfo - Get PMS info
- getIdentity - Get PMS identity
- getSourceConnectionInformation - Get Source Connection Information
- getTransientToken - Get Transient Tokens
- getAllHubs - Get global hubs
- getContinueWatching - Get the continue watching hub
- 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
- getLibraryItems - Get all items in library
- deleteCaches - Delete library caches
- cleanBundles - Clean bundles
- ingestTransientItem - Ingest a transient item
- getLibraryMatches - Get library matches
- optimizeDatabase - Optimize the Database
- getRandomArtwork - Get random artwork
- 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
- 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
- listSonicallySimilar - Get nearest tracks to metadata item
- setItemPreferences - Set metadata preferences
- refreshItemsMetadata - Refresh a metadata item
- getRelatedItems - Get related items
- listSimilar - Get similar items
- splitItem - Split a metadata item
- addSubtitles - Add 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
- updateItems - Set the fields of the filtered items
- startAnalysis - Analyze a section
- autocomplete - Get autocompletions for search
- getCollections - Get collections in a section
- getCommon - Get common fields for items
- emptyTrash - Empty section trash
- getSectionFilters - Get section filters
- getFirstCharacters - Get list of first characters
- deleteIndexes - Delete section indexes
- deleteIntros - Delete section intro markers
- getSectionPreferences - Get section prefs
- setSectionPreferences - Set section prefs
- cancelRefresh - Cancel section refresh
- refreshSection - Refresh section
- getAvailableSorts - Get a section sorts
- 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
- deleteCollectionItem - Delete an item from a collection
- moveCollectionItem - Reorder an item in the collection
- createPlaylist - Create a Playlist
- uploadPlaylist - Upload
- 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
- modifyPlaylistGenerator - Modify a Generator
- getPlaylistGeneratorItems - Get a playlist generator's items
- movePlaylistItem - Moving items in a playlist
- refreshPlaylist - Reprocess a generator
- getSessions - Get all sessions
- 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
- listPlaylists - List playlists
- getPlaylist - Retrieve Playlist
- getPlaylistItems - Retrieve Playlist Contents
- 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
- getAllPreferences - Get all preferences
- setPreferences - Set preferences
- getPreference - Get a preferences
- 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
- transcodeImage - Transcode an image
- makeDecision - Make a decision on media playback
- triggerFallback - Manually trigger a transcoder fallback
- transcodeSubtitles - Transcode subtitles
- startTranscodeSession - Start A Transcoding Session
- applyUpdates - Applying updates
- checkUpdates - Checking for updates
- getUpdatesStatus - Querying status of updates
PlexAPIError is the base class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
|---|---|---|
error.message |
string |
Error message |
error.statusCode |
number |
HTTP response status code eg 404 |
error.headers |
Headers |
HTTP response headers |
error.body |
string |
HTTP body. Can be empty string if no body is returned. |
error.rawResponse |
Response |
Raw HTTP response |
import { PlexAPI } from "@lukehagar/plexjs";
import * as errors from "@lukehagar/plexjs/sdk/models/errors";
import { Accepts } from "@lukehagar/plexjs/sdk/models/shared";
const plexAPI = new PlexAPI({
accepts: 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",
});
async function run() {
try {
const result = await plexAPI.general.getServerInfo({});
console.log(result);
} catch (error) {
if (error instanceof errors.PlexAPIError) {
console.log(error.message);
console.log(error.statusCode);
console.log(error.body);
console.log(error.headers);
}
}
}
run();Primary error:
PlexAPIError: The base class for HTTP error responses.
Less common errors (6)
Network errors:
ConnectionError: HTTP client was unable to make a request to a server.RequestTimeoutError: HTTP request timed out due to an AbortSignal signal.RequestAbortedError: HTTP request was aborted by the client.InvalidRequestError: Any input used to create a request is invalid.UnexpectedClientError: Unrecognised or unexpected error.
Inherit from PlexAPIError:
ResponseValidationError: Type mismatch between the data returned from the server and the structure expected by the SDK. Seeerror.rawValuefor the raw value anderror.pretty()for a nicely formatted multi-line string.
You can override the default server globally by passing a server index to the serverIdx: number optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the indexes associated with the available servers:
| # | Server | Variables | Description |
|---|---|---|---|
| 0 | https://{IP-description}.{identifier}.plex.direct:{port} |
identifierIP-descriptionport |
|
| 1 | {protocol}://{host}:{port} |
protocolhostport |
|
| 2 | https://{full_server_url} |
server_url |
If the selected server has variables, you may override its default values through the additional parameters made available in the SDK constructor:
| Variable | Parameter | Default | Description |
|---|---|---|---|
identifier |
identifier: 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. |
protocol |
protocol: string |
"http" |
The network protocol to use. Typically (http or https) |
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. |
server_url |
serverUrl: string |
"http://localhost:32400" |
The full manual URL to access the PMS |
import { PlexAPI } from "@lukehagar/plexjs";
import { Accepts } from "@lukehagar/plexjs/sdk/models/shared";
const plexAPI = new PlexAPI({
serverIdx: 1,
protocol: "<value>",
host: "electric-excess.name",
port: "36393",
accepts: 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",
});
async function run() {
const result = await plexAPI.general.getServerInfo({});
console.log(result);
}
run();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:
import { PlexAPI } from "@lukehagar/plexjs";
import { Accepts } from "@lukehagar/plexjs/sdk/models/shared";
const plexAPI = new PlexAPI({
serverURL: "https://{full_server_url}",
accepts: 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",
});
async function run() {
const result = await plexAPI.general.getServerInfo({});
console.log(result);
}
run();The TypeScript SDK makes API calls using an HTTPClient that wraps the native
Fetch API. This
client is a thin wrapper around fetch and 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 constructor takes an optional fetcher argument that can be
used to integrate a third-party HTTP client or when writing tests to mock out
the HTTP client and feed in fixtures.
The following example shows how to use the "beforeRequest" hook to to add a
custom header and a timeout to requests and how to use the "requestError" hook
to log errors:
import { PlexAPI } from "@lukehagar/plexjs";
import { HTTPClient } from "@lukehagar/plexjs/lib/http";
const httpClient = new HTTPClient({
// fetcher takes a function that has the same signature as native `fetch`.
fetcher: (request) => {
return fetch(request);
}
});
httpClient.addHook("beforeRequest", (request) => {
const nextRequest = new Request(request, {
signal: request.signal || AbortSignal.timeout(5000)
});
nextRequest.headers.set("x-custom-header", "custom value");
return nextRequest;
});
httpClient.addHook("requestError", (error, request) => {
console.group("Request Error");
console.log("Reason:", `${error}`);
console.log("Endpoint:", `${request.method} ${request.url}`);
console.groupEnd();
});
const sdk = new PlexAPI({ httpClient: httpClient });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:
import { PlexAPI } from "@lukehagar/plexjs";
import { Accepts } from "@lukehagar/plexjs/sdk/models/shared";
const plexAPI = new PlexAPI({
token: "<YOUR_API_KEY_HERE>",
accepts: 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",
});
async function run() {
const result = await plexAPI.general.getServerInfo({});
console.log(result);
}
run();For supported JavaScript runtimes, please consult RUNTIMES.md.
All the methods listed above are available as standalone functions. These functions are ideal for use in applications running in the browser, serverless runtimes or other environments where application bundle size is a primary concern. When using a bundler to build your application, all unused functionality will be either excluded from the final bundle or tree-shaken away.
To read more about standalone functions, check FUNCTIONS.md.
Available standalone functions
activitiesCancelActivity- Cancel a running activityactivitiesListActivities- Get all activitiesbutlerGetTasks- Get all Butler tasksbutlerStartTask- Start a single Butler taskbutlerStartTasks- Start all Butler tasksbutlerStopTask- Stop a single Butler taskbutlerStopTasks- Stop all Butler taskscollectionsCreateCollection- Create collectioncontentGetAlbums- Set section albumscontentGetAllLeaves- Set section leavescontentGetArts- Set section artworkcontentGetCategories- Set section categoriescontentGetCluster- Set section clusterscontentGetCollectionImage- Get a collection's imagecontentGetCollectionItems- Get items in a collectioncontentGetFolders- Get all folder locationscontentGetMetadataItem- Get a metadata itemcontentGetSonicallySimilar- The nearest audio trackscontentGetSonicPath- Similar tracks to transition from one to anothercontentListContent- Get items in the sectioncontentListMoments- Set section momentsdevicesAddDevice- Add a devicedevicesDiscoverDevices- Tell grabbers to discover devicesdevicesGetAvailableGrabbers- Get available grabbersdevicesGetDeviceDetails- Get device detailsdevicesGetDevicesChannels- Get a device's channelsdevicesGetThumb- Get device thumbdevicesListDevices- Get all devicesdevicesModifyDevice- Enable or disable a devicedevicesRemoveDevice- Remove a devicedevicesScan- Tell a device to scan for channelsdevicesSetChannelmap- Set a device's channel mappingdevicesSetDevicePreferences- Set device preferencesdevicesStopScan- Tell a device to stop scanning for channelsdownloadQueueAddDownloadQueueItems- Add to download queuedownloadQueueCreateDownloadQueue- Create download queuedownloadQueueGetDownloadQueue- Get a download queuedownloadQueueGetDownloadQueueItems- Get download queue itemsdownloadQueueGetDownloadQueueMedia- Grab download queue mediadownloadQueueGetItemDecision- Grab download queue item decisiondownloadQueueListDownloadQueueItems- Get download queue itemsdownloadQueueRemoveDownloadQueueItems- Delete download queue itemsdownloadQueueRestartProcessingDownloadQueueItems- Restart processing of items from the decisiondvRsAddDeviceToDVR- Add a device to an existing DVRdvRsAddLineup- Add a DVR LineupdvRsCreateDVR- Create a DVRdvRsDeleteDVR- Delete a single DVRdvRsDeleteLineup- Delete a DVR LineupdvRsGetDVR- Get a single DVRdvRsListDVRs- Get DVRsdvRsReloadGuide- Tell a DVR to reload program guidedvRsRemoveDeviceFromDVR- Remove a device from an existing DVRdvRsSetDVRPreferences- Set DVR preferencesdvRsStopDVRReload- Tell a DVR to stop reloading program guidedvRsTuneChannel- Tune a channel on a DVRepgComputeChannelMap- Compute the best channel mapepgGetAllLanguages- Get all languagesepgGetChannels- Get channels for a lineupepgGetCountries- Get all countriesepgGetCountriesLineups- Get lineups for a country via postal codeepgGetCountryRegions- Get regions for a countryepgGetLineup- Compute the best lineupepgGetLineupChannels- Get the channels for mulitple lineupsepgListLineups- Get lineups for a regioneventsConnectWebSocket- Connect to WebSocketeventsGetNotifications- Connect to EventsourcegeneralGetIdentity- Get PMS identitygeneralGetServerInfo- Get PMS infogeneralGetSourceConnectionInformation- Get Source Connection InformationgeneralGetTransientToken- Get Transient TokenshubsCreateCustomHub- Create a custom hubhubsDeleteCustomHub- Delete a custom hubhubsGetAllHubs- Get global hubshubsGetContinueWatching- Get the continue watching hubhubsGetHubItems- Get a hub's itemshubsGetMetadataHubs- Get hubs for section by metadata itemhubsGetPostplayHubs- Get postplay hubshubsGetPromotedHubs- Get the hubs which are promotedhubsGetRelatedHubs- Get related hubshubsGetSectionHubs- Get section hubshubsListHubs- Get hubshubsMoveHub- Move HubhubsResetSectionDefaults- Reset hubs to defaultshubsUpdateHubVisibility- Change hub visibilitylibraryAddExtras- Add to an item's extraslibraryAddSection- Add a library sectionlibraryAddSubtitles- Add subtitleslibraryAnalyzeMetadata- Analyze an itemlibraryAutocomplete- Get autocompletions for searchlibraryCancelRefresh- Cancel section refreshlibraryCleanBundles- Clean bundleslibraryCollectionsAddCollectionItems- Add items to a collectionlibraryCollectionsDeleteCollectionItem- Delete an item from a collectionlibraryCollectionsMoveCollectionItem- Reorder an item in the collectionlibraryCreateMarker- Create a markerlibraryDeleteCaches- Delete library cacheslibraryDeleteCollection- Delete a collectionlibraryDeleteIndexes- Delete section indexeslibraryDeleteIntros- Delete section intro markerslibraryDeleteLibrarySection- Delete a library sectionlibraryDeleteMarker- Delete a markerlibraryDeleteMediaItem- Delete a media itemlibraryDeleteMetadataItem- Delete a metadata itemlibraryDeleteStream- Delete a streamlibraryDetectAds- Ad-detect an itemlibraryDetectCredits- Credit detect a metadata itemlibraryDetectIntros- Intro detect an itemlibraryDetectVoiceActivity- Detect voice activitylibraryEditMarker- Edit a markerlibraryEditMetadataItem- Edit a metadata itemlibraryEditSection- Edit a library sectionlibraryEmptyTrash- Empty section trashlibraryGenerateThumbs- Generate thumbs of chapters for an itemlibraryGetAllItemLeaves- Get the leaves of an itemlibraryGetAugmentationStatus- Get augmentation statuslibraryGetAvailableSorts- Get a section sortslibraryGetChapterImage- Get a chapter imagelibraryGetCollections- Get collections in a sectionlibraryGetCommon- Get common fields for itemslibraryGetExtras- Get an item's extraslibraryGetFile- Get a file from a metadata or media bundlelibraryGetFirstCharacters- Get list of first characterslibraryGetImageFromBif- Get an image from part BIFlibraryGetItemArtwork- Get an item's artwork, theme, etclibraryGetItemTree- Get metadata items as a treelibraryGetLibraryDetails- Get a library section by idlibraryGetLibraryItems- Get all items in librarylibraryGetLibraryMatches- Get library matcheslibraryGetMediaPart- Get a media partlibraryGetPartIndex- Get BIF index for a partlibraryGetPerson- Get person detailslibraryGetRandomArtwork- Get random artworklibraryGetRelatedItems- Get related itemslibraryGetSectionFilters- Get section filterslibraryGetSectionImage- Get a section composite imagelibraryGetSectionPreferences- Get section prefslibraryGetSections- Get library sections (main Media Provider Only)libraryGetSectionsPrefs- Get section prefslibraryGetStream- Get a streamlibraryGetStreamLevels- Get loudness about a stream in jsonlibraryGetStreamLoudness- Get loudness about a streamlibraryGetTags- Get all library tags of a typelibraryIngestTransientItem- Ingest a transient itemlibraryListMatches- Get metadata matches for an itemlibraryListPersonMedia- Get media for a personlibraryListSimilar- Get similar itemslibraryListSonicallySimilar- Get nearest tracks to metadata itemlibraryListTopUsers- Get metadata top userslibraryMatchItem- Match a metadata itemlibraryMergeItems- Merge a metadata itemlibraryOptimizeDatabase- Optimize the DatabaselibraryPlaylistsAddPlaylistItems- Adding to a PlaylistlibraryPlaylistsClearPlaylistItems- Clearing a playlistlibraryPlaylistsCreatePlaylist- Create a PlaylistlibraryPlaylistsDeletePlaylist- Delete a PlaylistlibraryPlaylistsDeletePlaylistItem- Delete a GeneratorlibraryPlaylistsGetPlaylistGenerator- Get a playlist generatorlibraryPlaylistsGetPlaylistGeneratorItems- Get a playlist generator's itemslibraryPlaylistsGetPlaylistGenerators- Get a playlist's generatorslibraryPlaylistsModifyPlaylistGenerator- Modify a GeneratorlibraryPlaylistsMovePlaylistItem- Moving items in a playlistlibraryPlaylistsRefreshPlaylist- Reprocess a generatorlibraryPlaylistsUpdatePlaylist- Editing a PlaylistlibraryPlaylistsUploadPlaylist- UploadlibraryRefreshItemsMetadata- Refresh a metadata itemlibraryRefreshSection- Refresh sectionlibraryRefreshSectionsMetadata- Refresh all sectionslibrarySetItemArtwork- Set an item's artwork, theme, etclibrarySetItemPreferences- Set metadata preferenceslibrarySetSectionPreferences- Set section prefslibrarySetStreamOffset- Set a stream offsetlibrarySetStreamSelection- Set stream selectionlibrarySplitItem- Split a metadata itemlibraryStartAnalysis- Analyze a sectionlibraryStartBifGeneration- Start BIF generation of an itemlibraryStopAllRefreshes- Stop refreshlibraryUnmatch- Unmatch a metadata itemlibraryUpdateItemArtwork- Set an item's artwork, theme, etclibraryUpdateItems- Set the fields of the filtered itemsliveTVGetLiveTVSession- Get a single sessionliveTVGetSessionPlaylistIndex- Get a session playlist indexliveTVGetSessions- Get all sessionsliveTVGetSessionSegment- Get a single session segmentlogEnablePapertrail- Enabling PapertraillogWriteLog- Logging a multi-line message to the Plex Media Server loglogWriteMessage- Logging a single-line message to the Plex Media Server logplaylistGetPlaylist- Retrieve PlaylistplaylistGetPlaylistItems- Retrieve Playlist ContentsplaylistListPlaylists- List playlistsplayQueueAddToPlayQueue- Add a generator or playlist to a play queueplayQueueClearPlayQueue- Clear a play queueplayQueueCreatePlayQueue- Create a play queueplayQueueDeletePlayQueueItem- Delete an item from a play queueplayQueueGetPlayQueue- Retrieve a play queueplayQueueMovePlayQueueItem- Move an item in a play queueplayQueueResetPlayQueue- Reset a play queueplayQueueShuffle- Shuffle a play queueplayQueueUnshuffle- Unshuffle a play queuepreferencesGetAllPreferences- Get all preferencespreferencesGetPreference- Get a preferencespreferencesSetPreferences- Set preferencesproviderAddProvider- Add a media providerproviderDeleteMediaProvider- Delete a media providerproviderListProviders- Get the list of available media providersproviderRefreshProviders- Refresh media providersrateSetRating- Rate an itemsearchSearchHubs- Search HubsearchVoiceSearchHubs- Voice Search HubstatusDeleteHistory- Delete Single History ItemstatusGetBackgroundTasks- Get background tasksstatusGetHistoryItem- Get Single History ItemstatusListPlaybackHistory- List Playback HistorystatusListSessions- List SessionsstatusTerminateSession- Terminate a sessionsubscriptionsCancelGrab- Cancel an existing grabsubscriptionsCreateSubscription- Create a subscriptionsubscriptionsDeleteSubscription- Delete a subscriptionsubscriptionsEditSubscriptionPreferences- Edit a subscriptionsubscriptionsGetAllSubscriptions- Get all subscriptionssubscriptionsGetScheduledRecordings- Get all scheduled recordingssubscriptionsGetSubscription- Get a single subscriptionsubscriptionsGetTemplate- Get the subscription templatesubscriptionsProcessSubscriptions- Process all subscriptionssubscriptionsReorderSubscription- Re-order a subscriptiontimelineMarkPlayed- Mark an item as playedtimelineReport- Report media timelinetimelineUnscrobble- Mark an item as unplayedtranscoderMakeDecision- Make a decision on media playbacktranscoderStartTranscodeSession- Start A Transcoding SessiontranscoderTranscodeImage- Transcode an imagetranscoderTranscodeSubtitles- Transcode subtitlestranscoderTriggerFallback- Manually trigger a transcoder fallbackultraBlurGetColors- Get UltraBlur ColorsultraBlurGetImage- Get UltraBlur ImageupdaterApplyUpdates- Applying updatesupdaterCheckUpdates- Checking for updatesupdaterGetUpdatesStatus- Querying status of updates
Certain SDK methods accept files as part of a multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request.
Tip
Depending on your JavaScript runtime, there are convenient utilities that return a handle to a file without reading the entire contents into memory:
- Node.js v20+: Since v20, Node.js comes with a native
openAsBlobfunction innode:fs. - Bun: The native
Bun.filefunction produces a file handle that can be used for streaming file uploads. - Browsers: All supported browsers return an instance to a
Filewhen reading the value from an<input type="file">element. - Node.js v18: A file stream can be created using the
fileFromhelper fromfetch-blob/from.js.
import { PlexAPI } from "@lukehagar/plexjs";
import { openAsBlob } from "node:fs";
const plexAPI = new PlexAPI();
async function run() {
const result = await plexAPI.log.writeLog(await openAsBlob("example.file"));
console.log(result);
}
run();Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.
To change the default retry strategy for a single API call, simply provide a retryConfig object to the call:
import { PlexAPI } from "@lukehagar/plexjs";
import { Accepts } from "@lukehagar/plexjs/sdk/models/shared";
const plexAPI = new PlexAPI({
accepts: 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",
});
async function run() {
const result = await plexAPI.general.getServerInfo({}, {
retries: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
});
console.log(result);
}
run();If you'd like to override the default retry strategy for all operations that support retries, you can provide a retryConfig at SDK initialization:
import { PlexAPI } from "@lukehagar/plexjs";
import { Accepts } from "@lukehagar/plexjs/sdk/models/shared";
const plexAPI = new PlexAPI({
retryConfig: {
strategy: "backoff",
backoff: {
initialInterval: 1,
maxInterval: 50,
exponent: 1.1,
maxElapsedTime: 100,
},
retryConnectionErrors: false,
},
accepts: 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",
});
async function run() {
const result = await plexAPI.general.getServerInfo({});
console.log(result);
}
run();You can setup your SDK to emit debug logs for SDK requests and responses.
You can pass a logger that matches console's interface as an SDK option.
Warning
Beware that debug logging will reveal secrets, like API tokens in headers, in log messages printed to a console or files. It's recommended to use this feature only during local development and not in production.
import { PlexAPI } from "@lukehagar/plexjs";
const sdk = new PlexAPI({ debugLogger: console });This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally looking for the latest version.
While we value open-source contributions to this SDK, this library is generated programmatically. Feel free to open a PR or a Github issue as a proof of concept and we'll do our best to include it in a future release!