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.
To add the SDK as a dependency to your project:
go get github.com/LukeHagar/plexgopackage main
import (
"context"
"github.com/LukeHagar/plexgo"
"github.com/LukeHagar/plexgo/models/components"
"github.com/LukeHagar/plexgo/models/operations"
"log"
)
func main() {
ctx := context.Background()
s := plexgo.New(
plexgo.WithAccepts(components.AcceptsApplicationXML),
plexgo.WithClientIdentifier("abc123"),
plexgo.WithProduct("Plex for Roku"),
plexgo.WithVersion("2.4.1"),
plexgo.WithPlatform("Roku"),
plexgo.WithPlatformVersion("4.3 build 1057"),
plexgo.WithDevice("Roku 3"),
plexgo.WithModel("4200X"),
plexgo.WithDeviceVendor("Roku"),
plexgo.WithDeviceName("Living Room TV"),
plexgo.WithMarketplace("googlePlay"),
plexgo.WithSecurity("<YOUR_API_KEY_HERE>"),
)
res, err := s.Transcoder.StartTranscodeSession(ctx, operations.StartTranscodeSessionRequest{
TranscodeType: components.TranscodeTypeMusic,
AdvancedSubtitles: components.AdvancedSubtitlesBurn.ToPointer(),
Extension: operations.ExtensionMpd,
AudioBoost: plexgo.Pointer[int64](50),
AudioChannelCount: plexgo.Pointer[int64](5),
AutoAdjustQuality: components.BoolIntTrue.ToPointer(),
AutoAdjustSubtitle: components.BoolIntTrue.ToPointer(),
DirectPlay: components.BoolIntTrue.ToPointer(),
DirectStream: components.BoolIntTrue.ToPointer(),
DirectStreamAudio: components.BoolIntTrue.ToPointer(),
DisableResolutionRotation: components.BoolIntTrue.ToPointer(),
HasMDE: components.BoolIntTrue.ToPointer(),
Location: operations.StartTranscodeSessionQueryParamLocationWan.ToPointer(),
MediaBufferSize: plexgo.Pointer[int64](102400),
MediaIndex: plexgo.Pointer[int64](0),
MusicBitrate: plexgo.Pointer[int64](5000),
Offset: plexgo.Pointer[float64](90.5),
PartIndex: plexgo.Pointer[int64](0),
Path: plexgo.Pointer("/library/metadata/151671"),
PeakBitrate: plexgo.Pointer[int64](12000),
PhotoResolution: plexgo.Pointer("1080x1080"),
Protocol: operations.StartTranscodeSessionQueryParamProtocolDash.ToPointer(),
SecondsPerSegment: plexgo.Pointer[int64](5),
SubtitleSize: plexgo.Pointer[int64](50),
Subtitles: operations.StartTranscodeSessionQueryParamSubtitlesBurn.ToPointer(),
VideoResolution: plexgo.Pointer("1080x1080"),
Copyts: components.BoolIntTrue.ToPointer(),
VideoBitrate: plexgo.Pointer[int64](12000),
VideoQuality: plexgo.Pointer[int64](50),
XPlexClientProfileExtra: plexgo.Pointer("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: plexgo.Pointer("generic"),
})
if err != nil {
log.Fatal(err)
}
if res.TwoHundredApplicationVndAppleMpegurlBinaryResponse != nil {
// handle response
}
}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
- ModifyPlaylistGenerator - Modify a 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, simply provide a retry.Config object to the call by using the WithRetries option:
package main
import (
"context"
"github.com/LukeHagar/plexgo"
"github.com/LukeHagar/plexgo/models/components"
"github.com/LukeHagar/plexgo/models/operations"
"github.com/LukeHagar/plexgo/retry"
"log"
"models/operations"
)
func main() {
ctx := context.Background()
s := plexgo.New(
plexgo.WithAccepts(components.AcceptsApplicationXML),
plexgo.WithClientIdentifier("abc123"),
plexgo.WithProduct("Plex for Roku"),
plexgo.WithVersion("2.4.1"),
plexgo.WithPlatform("Roku"),
plexgo.WithPlatformVersion("4.3 build 1057"),
plexgo.WithDevice("Roku 3"),
plexgo.WithModel("4200X"),
plexgo.WithDeviceVendor("Roku"),
plexgo.WithDeviceName("Living Room TV"),
plexgo.WithMarketplace("googlePlay"),
plexgo.WithSecurity("<YOUR_API_KEY_HERE>"),
)
res, err := s.General.GetServerInfo(ctx, operations.GetServerInfoRequest{}, operations.WithRetries(
retry.Config{
Strategy: "backoff",
Backoff: &retry.BackoffStrategy{
InitialInterval: 1,
MaxInterval: 50,
Exponent: 1.1,
MaxElapsedTime: 100,
},
RetryConnectionErrors: false,
}))
if err != nil {
log.Fatal(err)
}
if res.Object != nil {
// handle response
}
}If you'd like to override the default retry strategy for all operations that support retries, you can use the WithRetryConfig option at SDK initialization:
package main
import (
"context"
"github.com/LukeHagar/plexgo"
"github.com/LukeHagar/plexgo/models/components"
"github.com/LukeHagar/plexgo/models/operations"
"github.com/LukeHagar/plexgo/retry"
"log"
)
func main() {
ctx := context.Background()
s := plexgo.New(
plexgo.WithRetryConfig(
retry.Config{
Strategy: "backoff",
Backoff: &retry.BackoffStrategy{
InitialInterval: 1,
MaxInterval: 50,
Exponent: 1.1,
MaxElapsedTime: 100,
},
RetryConnectionErrors: false,
}),
plexgo.WithAccepts(components.AcceptsApplicationXML),
plexgo.WithClientIdentifier("abc123"),
plexgo.WithProduct("Plex for Roku"),
plexgo.WithVersion("2.4.1"),
plexgo.WithPlatform("Roku"),
plexgo.WithPlatformVersion("4.3 build 1057"),
plexgo.WithDevice("Roku 3"),
plexgo.WithModel("4200X"),
plexgo.WithDeviceVendor("Roku"),
plexgo.WithDeviceName("Living Room TV"),
plexgo.WithMarketplace("googlePlay"),
plexgo.WithSecurity("<YOUR_API_KEY_HERE>"),
)
res, err := s.General.GetServerInfo(ctx, operations.GetServerInfoRequest{})
if err != nil {
log.Fatal(err)
}
if res.Object != nil {
// handle response
}
}Handling errors in this SDK should largely match your expectations. All operations return a response object or an error, they will never return both.
By Default, an API error will return sdkerrors.SDKError. When custom error responses are specified for an operation, the SDK may also return their associated error. You can refer to respective Errors tables in SDK docs for more details on possible error types for each operation.
For example, the GetServerInfo function may return the following errors:
| Error Type | Status Code | Content Type |
|---|---|---|
| sdkerrors.Error | 401 | application/json |
| sdkerrors.SDKError | 4XX, 5XX | */* |
package main
import (
"context"
"errors"
"github.com/LukeHagar/plexgo"
"github.com/LukeHagar/plexgo/models/components"
"github.com/LukeHagar/plexgo/models/operations"
"github.com/LukeHagar/plexgo/models/sdkerrors"
"log"
)
func main() {
ctx := context.Background()
s := plexgo.New(
plexgo.WithAccepts(components.AcceptsApplicationXML),
plexgo.WithClientIdentifier("abc123"),
plexgo.WithProduct("Plex for Roku"),
plexgo.WithVersion("2.4.1"),
plexgo.WithPlatform("Roku"),
plexgo.WithPlatformVersion("4.3 build 1057"),
plexgo.WithDevice("Roku 3"),
plexgo.WithModel("4200X"),
plexgo.WithDeviceVendor("Roku"),
plexgo.WithDeviceName("Living Room TV"),
plexgo.WithMarketplace("googlePlay"),
plexgo.WithSecurity("<YOUR_API_KEY_HERE>"),
)
res, err := s.General.GetServerInfo(ctx, operations.GetServerInfoRequest{})
if err != nil {
var e *sdkerrors.Error
if errors.As(err, &e) {
// handle error
log.Fatal(e.Error())
}
var e *sdkerrors.SDKError
if errors.As(err, &e) {
// handle error
log.Fatal(e.Error())
}
}
}You can override the default server globally using the WithServerIndex(serverIndex int) option 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 option(s):
| Variable | Option | Default | Description |
|---|---|---|---|
identifier |
WithIdentifier(identifier string) |
"0123456789abcdef0123456789abcdef" |
The unique identifier of this particular PMS |
IP-description |
WithIPDescription(ipDescription string) |
"1-2-3-4" |
A - separated string of the IPv4 or IPv6 address components |
port |
WithPort(port string) |
"32400" |
The Port number configured on the PMS. Typically (32400). If using a reverse proxy, this would be the port number configured on the proxy. |
host |
WithHost(host string) |
"localhost" |
The Host of the PMS. If using on a local network, this is the internal IP address of the server hosting the PMS. If using on an external network, this is the external IP address for your network, and requires port forwarding. If using a reverse proxy, this would be the external DNS domain for your network, and requires the proxy handle port forwarding. |
protocol |
WithProtocol(protocol string) |
"http" |
The network protocol to use. Typically (http or https) |
full_server_url |
WithFullServerURL(fullServerURL string) |
"http://localhost:32400" |
The full manual URL to access the PMS |
package main
import (
"context"
"github.com/LukeHagar/plexgo"
"github.com/LukeHagar/plexgo/models/components"
"github.com/LukeHagar/plexgo/models/operations"
"log"
)
func main() {
ctx := context.Background()
s := plexgo.New(
plexgo.WithServerIndex(0),
plexgo.WithIdentifier("0123456789abcdef0123456789abcdef"),
plexgo.WithIPDescription("1-2-3-4"),
plexgo.WithPort("32400"),
plexgo.WithAccepts(components.AcceptsApplicationXML),
plexgo.WithClientIdentifier("abc123"),
plexgo.WithProduct("Plex for Roku"),
plexgo.WithVersion("2.4.1"),
plexgo.WithPlatform("Roku"),
plexgo.WithPlatformVersion("4.3 build 1057"),
plexgo.WithDevice("Roku 3"),
plexgo.WithModel("4200X"),
plexgo.WithDeviceVendor("Roku"),
plexgo.WithDeviceName("Living Room TV"),
plexgo.WithMarketplace("googlePlay"),
plexgo.WithSecurity("<YOUR_API_KEY_HERE>"),
)
res, err := s.General.GetServerInfo(ctx, operations.GetServerInfoRequest{})
if err != nil {
log.Fatal(err)
}
if res.Object != nil {
// handle response
}
}The default server can also be overridden globally using the WithServerURL(serverURL string) option when initializing the SDK client instance. For example:
package main
import (
"context"
"github.com/LukeHagar/plexgo"
"github.com/LukeHagar/plexgo/models/components"
"github.com/LukeHagar/plexgo/models/operations"
"log"
)
func main() {
ctx := context.Background()
s := plexgo.New(
plexgo.WithServerURL("https://http://localhost:32400"),
plexgo.WithAccepts(components.AcceptsApplicationXML),
plexgo.WithClientIdentifier("abc123"),
plexgo.WithProduct("Plex for Roku"),
plexgo.WithVersion("2.4.1"),
plexgo.WithPlatform("Roku"),
plexgo.WithPlatformVersion("4.3 build 1057"),
plexgo.WithDevice("Roku 3"),
plexgo.WithModel("4200X"),
plexgo.WithDeviceVendor("Roku"),
plexgo.WithDeviceName("Living Room TV"),
plexgo.WithMarketplace("googlePlay"),
plexgo.WithSecurity("<YOUR_API_KEY_HERE>"),
)
res, err := s.General.GetServerInfo(ctx, operations.GetServerInfoRequest{})
if err != nil {
log.Fatal(err)
}
if res.Object != nil {
// handle response
}
}The server URL can also be overridden on a per-operation basis, provided a server list was specified for the operation. For example:
package main
import (
"context"
"github.com/LukeHagar/plexgo"
"github.com/LukeHagar/plexgo/models/operations"
"log"
)
func main() {
ctx := context.Background()
s := plexgo.New(
plexgo.WithSecurity("<YOUR_API_KEY_HERE>"),
)
res, err := s.General.GetUserWebhooks(ctx, operations.WithServerURL("https://plex.tv/api/v2"))
if err != nil {
log.Fatal(err)
}
if res.WebhookPayload != nil {
// handle response
}
}The Go SDK makes API calls that wrap an internal HTTP client. The requirements for the HTTP client are very simple. It must match this interface:
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}The built-in net/http client satisfies this interface and a default client based on the built-in is provided by default. To replace this default with a client of your own, you can implement this interface yourself or provide your own client configured as desired. Here's a simple example, which adds a client with a 30 second timeout.
import (
"net/http"
"time"
"github.com/LukeHagar/plexgo"
)
var (
httpClient = &http.Client{Timeout: 30 * time.Second}
sdkClient = plexgo.New(plexgo.WithClient(httpClient))
)This can be a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration.
This SDK supports the following security scheme globally:
| Name | Type | Scheme |
|---|---|---|
Token |
apiKey | API key |
You can configure it using the WithSecurity option when initializing the SDK client instance. For example:
package main
import (
"context"
"github.com/LukeHagar/plexgo"
"github.com/LukeHagar/plexgo/models/components"
"github.com/LukeHagar/plexgo/models/operations"
"log"
)
func main() {
ctx := context.Background()
s := plexgo.New(
plexgo.WithSecurity("<YOUR_API_KEY_HERE>"),
plexgo.WithAccepts(components.AcceptsApplicationXML),
plexgo.WithClientIdentifier("abc123"),
plexgo.WithProduct("Plex for Roku"),
plexgo.WithVersion("2.4.1"),
plexgo.WithPlatform("Roku"),
plexgo.WithPlatformVersion("4.3 build 1057"),
plexgo.WithDevice("Roku 3"),
plexgo.WithModel("4200X"),
plexgo.WithDeviceVendor("Roku"),
plexgo.WithDeviceName("Living Room TV"),
plexgo.WithMarketplace("googlePlay"),
)
res, err := s.General.GetServerInfo(ctx, operations.GetServerInfoRequest{})
if err != nil {
log.Fatal(err)
}
if res.Object != nil {
// handle response
}
}Some operations in this SDK require the security scheme to be specified at the request level. For example:
package main
import (
"context"
"github.com/LukeHagar/plexgo"
"github.com/LukeHagar/plexgo/models/components"
"github.com/LukeHagar/plexgo/models/operations"
"log"
)
func main() {
ctx := context.Background()
s := plexgo.New(
plexgo.WithAccepts(components.AcceptsApplicationXML),
plexgo.WithClientIdentifier("abc123"),
plexgo.WithProduct("Plex for Roku"),
plexgo.WithVersion("2.4.1"),
plexgo.WithPlatform("Roku"),
plexgo.WithPlatformVersion("4.3 build 1057"),
plexgo.WithDevice("Roku 3"),
plexgo.WithModel("4200X"),
plexgo.WithDeviceVendor("Roku"),
plexgo.WithDeviceName("Living Room TV"),
plexgo.WithMarketplace("googlePlay"),
)
res, err := s.Authentication.CreateOAuthPin(ctx, operations.CreateOAuthPinRequest{}, operations.CreateOAuthPinSecurity{
ClientIdentifier: "<YOUR_API_KEY_HERE>",
})
if err != nil {
log.Fatal(err)
}
if res.Object != nil {
// handle response
}
}This SDK defines the following custom types to assist with marshalling and unmarshalling data.
types.Date is a wrapper around time.Time that allows for JSON marshaling a date string formatted as "2006-01-02".
d1 := types.NewDate(time.Now()) // returns *types.Date
d2 := types.DateFromTime(time.Now()) // returns types.Date
d3, err := types.NewDateFromString("2019-01-01") // returns *types.Date, error
d4, err := types.DateFromString("2019-01-01") // returns types.Date, error
d5 := types.MustNewDateFromString("2019-01-01") // returns *types.Date and panics on error
d6 := types.MustDateFromString("2019-01-01") // returns types.Date and panics on errorThis 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!