YouTube Music API (Unofficial)

1.11.5 · active · verified Thu Apr 16

ytmusicapi is a Python 3 library that provides an unofficial API for interacting with YouTube Music. It emulates web client requests using user cookie data for authentication, allowing for browsing, library management, playlist manipulation, and more. The current version is 1.11.5 and it maintains an active release cadence with frequent updates. [1, 7]

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `ytmusicapi` for both authenticated and unauthenticated requests. It shows a basic search for a song and retrieving the first few library playlists. Authentication typically requires either an `oauth.json` or `browser.json` file, which should be generated by following the detailed steps in the official ytmusicapi documentation. For a secure production environment, the path to this authentication file should be managed via environment variables. [1, 2, 3, 4]

import os
from ytmusicapi import YTMusic

# --- Authentication (choose one) ---
# Option 1: Using browser headers (recommended for personal use)
# Create 'browser.json' by following instructions in the ytmusicapi documentation (developer tools network tab -> copy as cURL).
# For programmatic setup, use `from ytmusicapi.auth.browser import setup_browser`
# Example: yt = YTMusic('browser.json')

# Option 2: Using OAuth (requires Google Cloud Project setup, often more stable for automated scripts)
# Create 'oauth.json' by following instructions in the ytmusicapi documentation (Google Cloud Console -> OAuth client ID).
# Example: yt = YTMusic('oauth.json')

# For unauthenticated requests (limited functionality):
yt = YTMusic()

# Use an environment variable for the auth file path in production
auth_file = os.environ.get('YTMUSIC_AUTH_FILE', 'oauth.json') # or 'browser.json'

try:
    yt = YTMusic(auth_file)
    # Perform a search
    search_results = yt.search('Eminem Lose Yourself', filter='songs')
    if search_results:
        print(f"Found song: {search_results[0]['title']} by {search_results[0]['artist']['name']}")
    else:
        print("No results found.")

    # Get library playlists
    playlists = yt.get_library_playlists(limit=5)
    if playlists:
        print("\nYour first 5 library playlists:")
        for playlist in playlists:
            print(f"- {playlist['title']} (ID: {playlist['playlistId']})")
    else:
        print("No library playlists found.")

except Exception as e:
    print(f"An error occurred: {e}")
    print("Please ensure your authentication file (oauth.json or browser.json) is correctly set up and accessible.")

view raw JSON →