To add the NuGet package to a .NET project:
dotnet add package LukeHagar.PlexAPI.SDKTo add a reference to a local instance of the SDK in a .NET project:
dotnet add reference LukeHagar/PlexAPI/SDK/LukeHagar.PlexAPI.SDK.csprojusing LukeHagar.PlexAPI.SDK;
using LukeHagar.PlexAPI.SDK.Models.Components;
using LukeHagar.PlexAPI.SDK.Models.Requests;
var sdk = new PlexAPI(
accepts: LukeHagar.PlexAPI.SDK.Models.Components.Accepts.ApplicationXml,
clientIdentifier: "abc123",
product: "Plex for Roku",
version: "2.4.1",
platform: "Roku",
platformVersion: "4.3 build 1057",
device: "Roku 3",
model: "4200X",
deviceVendor: "Roku",
deviceName: "Living Room TV",
marketplace: "googlePlay",
token: "<YOUR_API_KEY_HERE>"
);
StartTranscodeSessionRequest req = new StartTranscodeSessionRequest() {
TranscodeType = TranscodeType.Music,
Extension = Extension.Mpd,
AdvancedSubtitles = LukeHagar.PlexAPI.SDK.Models.Components.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 = StartTranscodeSessionQueryParamLocation.Wan,
MediaBufferSize = 102400,
MediaIndex = 0,
MusicBitrate = 5000,
Offset = 90.5D,
PartIndex = 0,
Path = "/library/metadata/151671",
PeakBitrate = 12000,
PhotoResolution = "1080x1080",
Protocol = StartTranscodeSessionQueryParamProtocol.Dash,
SecondsPerSegment = 5,
SubtitleSize = 50,
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",
};
var res = await sdk.Transcoder.StartTranscodeSessionAsync(req);
// handle responseAvailable 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
- 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
You can override the default server globally by passing a server index to the serverIndex: int optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the indexes associated with the available servers:
| # | Server | Variables | Description |
|---|---|---|---|
| 0 | https://{IP-description}.{identifier}.plex.direct:{port} |
identifierIP-descriptionport |
|
| 1 | {protocol}://{host}:{port} |
protocolhostport |
|
| 2 | https://{full_server_url} |
full_server_url |
If the selected server has variables, you may override its default values through the additional parameters made available in the SDK constructor:
| Variable | Parameter | Default | Description |
|---|---|---|---|
identifier |
identifier: string |
"0123456789abcdef0123456789abcdef" |
The unique identifier of this particular PMS |
IP-description |
ipDescription: string |
"1-2-3-4" |
A - separated string of the IPv4 or IPv6 address components |
port |
port: string |
"32400" |
The Port number configured on the PMS. Typically (32400). If using a reverse proxy, this would be the port number configured on the proxy. |
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. |
full_server_url |
fullServerUrl: string |
"http://localhost:32400" |
The full manual URL to access the PMS |
using LukeHagar.PlexAPI.SDK;
using LukeHagar.PlexAPI.SDK.Models.Components;
using LukeHagar.PlexAPI.SDK.Models.Requests;
var sdk = new PlexAPI(
serverIndex: 0,
identifier: "0123456789abcdef0123456789abcdef",
ipDescription: "1-2-3-4",
port: "32400",
accepts: LukeHagar.PlexAPI.SDK.Models.Components.Accepts.ApplicationXml,
clientIdentifier: "abc123",
product: "Plex for Roku",
version: "2.4.1",
platform: "Roku",
platformVersion: "4.3 build 1057",
device: "Roku 3",
model: "4200X",
deviceVendor: "Roku",
deviceName: "Living Room TV",
marketplace: "googlePlay",
token: "<YOUR_API_KEY_HERE>"
);
GetServerInfoRequest req = new GetServerInfoRequest() {};
var res = await sdk.General.GetServerInfoAsync(req);
// handle responseThe default server can also be overridden globally by passing a URL to the serverUrl: string optional parameter when initializing the SDK client instance. For example:
using LukeHagar.PlexAPI.SDK;
using LukeHagar.PlexAPI.SDK.Models.Components;
using LukeHagar.PlexAPI.SDK.Models.Requests;
var sdk = new PlexAPI(
serverUrl: "https://http://localhost:32400",
accepts: LukeHagar.PlexAPI.SDK.Models.Components.Accepts.ApplicationXml,
clientIdentifier: "abc123",
product: "Plex for Roku",
version: "2.4.1",
platform: "Roku",
platformVersion: "4.3 build 1057",
device: "Roku 3",
model: "4200X",
deviceVendor: "Roku",
deviceName: "Living Room TV",
marketplace: "googlePlay",
token: "<YOUR_API_KEY_HERE>"
);
GetServerInfoRequest req = new GetServerInfoRequest() {};
var res = await sdk.General.GetServerInfoAsync(req);
// handle responseThis SDK supports the following security scheme globally:
| Name | Type | Scheme |
|---|---|---|
Token |
apiKey | API key |
To authenticate with the API the Token parameter must be set when initializing the SDK client instance. For example:
using LukeHagar.PlexAPI.SDK;
using LukeHagar.PlexAPI.SDK.Models.Components;
using LukeHagar.PlexAPI.SDK.Models.Requests;
var sdk = new PlexAPI(
token: "<YOUR_API_KEY_HERE>",
accepts: LukeHagar.PlexAPI.SDK.Models.Components.Accepts.ApplicationXml,
clientIdentifier: "abc123",
product: "Plex for Roku",
version: "2.4.1",
platform: "Roku",
platformVersion: "4.3 build 1057",
device: "Roku 3",
model: "4200X",
deviceVendor: "Roku",
deviceName: "Living Room TV",
marketplace: "googlePlay"
);
GetServerInfoRequest req = new GetServerInfoRequest() {};
var res = await sdk.General.GetServerInfoAsync(req);
// handle responsePlexAPIError is the base exception class for all HTTP error responses. It has the following properties:
| Property | Type | Description |
|---|---|---|
Message |
string | Error message |
StatusCode |
int | HTTP status code |
Headers |
HttpResponseHeaders | HTTP headers |
ContentType |
string? | HTTP content type |
RawResponse |
HttpResponseMessage | HTTP response object |
Body |
string | HTTP response body |
using LukeHagar.PlexAPI.SDK;
using LukeHagar.PlexAPI.SDK.Models.Components;
using LukeHagar.PlexAPI.SDK.Models.Errors;
using LukeHagar.PlexAPI.SDK.Models.Requests;
var sdk = new PlexAPI(
accepts: LukeHagar.PlexAPI.SDK.Models.Components.Accepts.ApplicationXml,
clientIdentifier: "abc123",
product: "Plex for Roku",
version: "2.4.1",
platform: "Roku",
platformVersion: "4.3 build 1057",
device: "Roku 3",
model: "4200X",
deviceVendor: "Roku",
deviceName: "Living Room TV",
marketplace: "googlePlay",
token: "<YOUR_API_KEY_HERE>"
);
try
{
GetServerInfoRequest req = new GetServerInfoRequest() {};
var res = await sdk.General.GetServerInfoAsync(req);
// handle response
}
catch (PlexAPIError ex) // all SDK exceptions inherit from PlexAPIError
{
// ex.ToString() provides a detailed error message
System.Console.WriteLine(ex);
// Base exception fields
HttpResponseMessage rawResponse = ex.RawResponse;
HttpResponseHeaders headers = ex.Headers;
int statusCode = ex.StatusCode;
string? contentType = ex.ContentType;
var responseBody = ex.Body;
}
catch (System.Net.Http.HttpRequestException ex)
{
// Check ex.InnerException for Network connectivity errors
}Primary exception:
PlexAPIError: The base class for HTTP error responses.
Less common exceptions (2)
-
System.Net.Http.HttpRequestException: Network connectivity error. For more details about the underlying cause, inspect theex.InnerException. -
Inheriting from
PlexAPIError:ResponseValidationError: Thrown when the response data could not be deserialized into the expected type.
The C# SDK makes API calls using an ISpeakeasyHttpClient that wraps the native
HttpClient. This
client provides the ability to attach hooks around the request lifecycle that can be used to modify the request or handle
errors and response.
The ISpeakeasyHttpClient interface allows you to either use the default SpeakeasyHttpClient that comes with the SDK,
or provide your own custom implementation with customized configuration such as custom message handlers, timeouts,
connection pooling, and other HTTP client settings.
The following example shows how to create a custom HTTP client with request modification and error handling:
using LukeHagar.PlexAPI.SDK;
using LukeHagar.PlexAPI.SDK.Utils;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
// Create a custom HTTP client
public class CustomHttpClient : ISpeakeasyHttpClient
{
private readonly ISpeakeasyHttpClient _defaultClient;
public CustomHttpClient()
{
_defaultClient = new SpeakeasyHttpClient();
}
public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
{
// Add custom header and timeout
request.Headers.Add("x-custom-header", "custom value");
request.Headers.Add("x-request-timeout", "30");
try
{
var response = await _defaultClient.SendAsync(request, cancellationToken);
// Log successful response
Console.WriteLine($"Request successful: {response.StatusCode}");
return response;
}
catch (Exception error)
{
// Log error
Console.WriteLine($"Request failed: {error.Message}");
throw;
}
}
public void Dispose()
{
_httpClient?.Dispose();
_defaultClient?.Dispose();
}
}
// Use the custom HTTP client with the SDK
var customHttpClient = new CustomHttpClient();
var sdk = new PlexAPI(client: customHttpClient);You can also provide a completely custom HTTP client with your own configuration:
using LukeHagar.PlexAPI.SDK.Utils;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
// Custom HTTP client with custom configuration
public class AdvancedHttpClient : ISpeakeasyHttpClient
{
private readonly HttpClient _httpClient;
public AdvancedHttpClient()
{
var handler = new HttpClientHandler()
{
MaxConnectionsPerServer = 10,
// ServerCertificateCustomValidationCallback = customCertValidation, // Custom SSL validation if needed
};
_httpClient = new HttpClient(handler)
{
Timeout = TimeSpan.FromSeconds(30)
};
}
public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
{
return await _httpClient.SendAsync(request, cancellationToken ?? CancellationToken.None);
}
public void Dispose()
{
_httpClient?.Dispose();
}
}
var sdk = PlexAPI.Builder()
.WithClient(new AdvancedHttpClient())
.Build();For simple debugging, you can enable request/response logging by implementing a custom client:
public class LoggingHttpClient : ISpeakeasyHttpClient
{
private readonly ISpeakeasyHttpClient _innerClient;
public LoggingHttpClient(ISpeakeasyHttpClient innerClient = null)
{
_innerClient = innerClient ?? new SpeakeasyHttpClient();
}
public async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken? cancellationToken = null)
{
// Log request
Console.WriteLine($"Sending {request.Method} request to {request.RequestUri}");
var response = await _innerClient.SendAsync(request, cancellationToken);
// Log response
Console.WriteLine($"Received {response.StatusCode} response");
return response;
}
public void Dispose() => _innerClient?.Dispose();
}
var sdk = new PlexAPI(client: new LoggingHttpClient());The SDK also provides built-in hook support through the SDKConfiguration.Hooks system, which automatically handles
BeforeRequestAsync, AfterSuccessAsync, and AfterErrorAsync hooks for advanced request lifecycle management.
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!