Build Custom Plex Integrations With the API
The Plex API gives programmatic access to your server's libraries, playback sessions, user management, and system status. You can build dashboards, automate library maintenance, trigger actions on playback events, and integrate Plex with other services in your home lab. This guide covers authentication, the most useful endpoints, webhooks, and practical integration patterns.
Authentication
Getting a Plex Token
Every API request requires a Plex authentication token (X-Plex-Token). The easiest way to find your token:
- Open the Plex Web UI and navigate to any library item.
- Click the three-dot menu on the item and select Get Info, then View XML.
- The URL in your browser contains X-Plex-Token= followed by your token string.
Alternatively, obtain a token programmatically by sending a POST request to the Plex authentication endpoint with your Plex account credentials. The response includes the authToken field.
Token Security
Your Plex token grants full access to your server. Treat it like a password:
- Never commit tokens to version control or public repositories.
- Store tokens in environment variables or a secrets manager.
- Rotate the token periodically by signing out of all devices and signing back in.
API Basics
Base URL
All API requests go to your server's address with the token appended:
http://YOUR_SERVER_IP:32400/endpoint?X-Plex-Token=YOUR_TOKEN
For remote access, use your server's public address or plex.tv relay URL.
Response Formats
The Plex API returns XML by default. To receive JSON (easier to parse in most languages), add the Accept header:
Accept: application/json
Required Headers
Some endpoints require identification headers alongside the token:
- X-Plex-Client-Identifier: A unique string identifying your application.
- X-Plex-Product: The name of your application.
- X-Plex-Version: Your application version.
These headers prevent your integration from being mistaken for an unauthorized client and help Plex track API usage.
Library Endpoints
List All Libraries
GET /library/sections returns all libraries on the server. Each library has a key (section ID) used in subsequent requests. The response includes the library type (movie, show, artist, photo), title, and content statistics.
Browse Library Contents
GET /library/sections/{sectionKey}/all returns every item in a library. For large libraries, this response can be substantial — use the X-Plex-Container-Start and X-Plex-Container-Size headers for pagination.
Get Item Metadata
GET /library/metadata/{ratingKey} returns detailed metadata for a specific item including title, year, summary, genres, actors, file information, and media details (codec, resolution, bitrate).
Search
GET /search?query=TERM searches across all libraries. Add the type parameter to filter by content type: type=1 for movies, type=2 for TV shows, type=8 for music.
Playback and Session Endpoints
Active Sessions
GET /status/sessions returns all currently playing streams. Each session includes the user, client device, media being played, playback progress, transcode status, and bandwidth usage. This is the same data shown on the Plex Dashboard.
Session History
GET /status/sessions/history/all returns recent playback history across all users. Use query parameters to filter by date, user, or library.
Terminate a Session
GET /status/sessions/terminate?sessionId=SESSION_ID&reason=MESSAGE stops a specific playback session. The user sees the reason message on their client. Useful for automated bandwidth management or restricting simultaneous streams.
Library Maintenance
Trigger a Library Scan
GET /library/sections/{sectionKey}/refresh starts a library scan for the specified section. The scan runs asynchronously — the API returns immediately while the scan continues in the background.
Refresh Metadata
PUT /library/metadata/{ratingKey}/refresh forces a metadata refresh for a specific item. Useful after fixing incorrect matches or when new metadata is available from the agent.
Empty Trash
PUT /library/sections/{sectionKey}/emptyTrash permanently removes items in the library trash. Items are trashed when their files are deleted from disk — this endpoint cleans up the database entries.
Webhooks
Plex webhooks push real-time event notifications to a URL you configure. Webhooks require Plex Pass.
Setting Up Webhooks
- Go to Settings, Webhooks in the Plex Web UI.
- Add a webhook URL — the endpoint where Plex sends event notifications.
- Plex sends a POST request to this URL whenever a supported event occurs.
Supported Events
- media.play: A user starts playing media.
- media.pause: A user pauses playback.
- media.resume: A user resumes paused playback.
- media.stop: A user stops playback.
- media.scrobble: A user finishes watching an item (passes the scrobble threshold).
- library.new: New media is added to a library.
- library.on.deck: An item is added to On Deck.
- admin.database.backup: The database backup task completes.
- admin.database.corrupted: Database corruption is detected.
Webhook Payload
Each webhook sends a JSON payload containing the event type, the user who triggered it, the media item details, and the server information. Parse this payload to trigger automations based on specific events.
Practical Integration Examples
Discord Notifications
Send a message to a Discord channel when new media is added to Plex. Set up a webhook handler that receives Plex library.new events and forwards a formatted message to a Discord webhook URL. Include the title, year, poster image, and library name in the Discord embed.
Smart Home Integration
Dim lights when playback starts, restore when it stops. Use media.play and media.stop webhooks to trigger smart home automations via Home Assistant or similar platforms. Filter by player device to only trigger for the living room TV, not phone playback.
Bandwidth Monitor
Poll the active sessions endpoint on a schedule and log bandwidth usage over time. Alert when total bandwidth exceeds a threshold or when a specific user is consuming excessive resources. This provides monitoring similar to Tautulli but customized to your specific needs.
Automated Library Cleanup
Script that queries all libraries, identifies media files not played in a specified number of days, and either moves them to a holding directory or generates a report for manual review. Use the last played date from metadata to determine staleness.
Rate Limiting and Best Practices
- The Plex API does not enforce strict rate limits for local requests, but avoid hammering the server with rapid successive calls. A polling interval of 5-10 seconds is reasonable for session monitoring.
- Cache library metadata locally rather than re-fetching on every request. Libraries change infrequently — poll for changes rather than re-downloading the full library on each check.
- Use webhooks instead of polling whenever possible. Webhooks push events in real time without any server polling overhead.
- Test API integrations against a non-production library first to avoid accidentally modifying your main library data.