Skip to content

Plex API

Automate Plex with the REST API.

Terminal window
# Method 1: From Plex Web
# Sign in → Browser DevTools → Network tab → Look for X-Plex-Token
# Method 2: API
curl -u "username:password" \
"https://plex.tv/users/sign_in.xml" \
-X POST \
-H "X-Plex-Client-Identifier: MyApp"
Terminal window
# Identity
curl "http://localhost:32400/identity?X-Plex-Token=TOKEN"
# Server capabilities
curl "http://localhost:32400/?X-Plex-Token=TOKEN"
Terminal window
# List libraries
curl "http://localhost:32400/library/sections?X-Plex-Token=TOKEN"
# Get library contents
curl "http://localhost:32400/library/sections/1/all?X-Plex-Token=TOKEN"
# Refresh library
curl -X POST "http://localhost:32400/library/sections/1/refresh?X-Plex-Token=TOKEN"
Terminal window
# Search all
curl "http://localhost:32400/search?query=inception&X-Plex-Token=TOKEN"
# Search library
curl "http://localhost:32400/library/sections/1/search?query=inception&X-Plex-Token=TOKEN"
Terminal window
# Currently playing
curl "http://localhost:32400/status/sessions?X-Plex-Token=TOKEN"
Terminal window
pip install plexapi
from plexapi.server import PlexServer
plex = PlexServer('http://localhost:32400', 'YOUR_TOKEN')
# List libraries
for section in plex.library.sections():
print(f"{section.title}: {section.totalSize} items")
# Search
results = plex.search('Inception')
# Refresh library
movies = plex.library.section('Movies')
movies.refresh()
# Get item details
movie = plex.library.section('Movies').get('Inception')
print(f"Rating: {movie.rating}")
print(f"Bitrate: {movie.media[0].bitrate}")
#!/usr/bin/env python3
"""Plex library maintenance script."""
from plexapi.server import PlexServer
import os
PLEX_URL = os.getenv('PLEX_URL', 'http://localhost:32400')
PLEX_TOKEN = os.getenv('PLEX_TOKEN')
def main():
plex = PlexServer(PLEX_URL, PLEX_TOKEN)
# Refresh all libraries
for section in plex.library.sections():
print(f"Refreshing {section.title}...")
section.refresh()
# Clean bundles
plex.library.cleanBundles()
# Optimize database
plex.library.optimize()
if __name__ == "__main__":
main()

Configure webhooks for events:

  1. SettingsWebhooks
  2. Add webhook URL
  3. Events sent as POST requests

Example payload:

{
"event": "media.play",
"user": true,
"owner": true,
"Account": {
"title": "username"
},
"Metadata": {
"title": "Movie Title",
"type": "movie"
}
}
  • Be respectful of API limits
  • Cache responses when possible
  • Use webhooks instead of polling