Reference

Reference for the YTMusic class.

class ytmusicapi.YTMusic(auth: str = None, user: str = None, requests_session=True, proxies: dict = None, language: str = 'en')

Allows automated interactions with YouTube Music by emulating the YouTube web client’s requests. Permits both authenticated and non-authenticated requests. Authentication header data must be provided on initialization.

YTMusic.__init__(auth: str = None, user: str = None, requests_session=True, proxies: dict = None, language: str = 'en')

Create a new instance to interact with YouTube Music.

Parameters:
  • auth – Optional. Provide a string or path to file. Authentication credentials are needed to manage your library. Should be an adjusted version of headers_auth.json.example in the project root. See setup() for how to fill in the correct credentials. Default: A default header is used without authentication.
  • user – Optional. Specify a user ID string to use in requests. This is needed if you want to send requests on behalf of a brand account. Otherwise the default account is used. You can retrieve the user ID by going to https://myaccount.google.com/brandaccounts and selecting your brand account. The user ID will be in the URL: https://myaccount.google.com/b/user_id/
  • requests_session – A Requests session object or a truthy value to create one. A falsy value disables sessions. It is generally a good idea to keep sessions enabled for performance reasons (connection pooling).
  • proxies

    Optional. Proxy configuration in requests format.

  • language – Optional. Can be used to change the language of returned data. English will be used by default. Available languages can be checked in the ytmusicapi/locales directory.

Setup

See also the Setup page

classmethod YTMusic.setup(filepath: str = None, headers_raw: str = None) → Dict[KT, VT]

Requests browser headers from the user via command line and returns a string that can be passed to YTMusic()

Parameters:
  • filepath – Optional filepath to store headers to.
  • headers_raw – Optional request headers copied from browser. Otherwise requested from terminal
Returns:

configuration headers string

Browsing

YTMusic.get_artist(channelId: str) → Dict[KT, VT]

Get information about an artist and their top releases (songs, albums, singles and videos). The top lists contain pointers for getting the full list of releases. For songs/videos, pass the browseId to get_playlist(). For albums/singles, pass browseId and params to get_artist_albums().

Parameters:channelId – channel id of the artist
Returns:Dictionary with requested information.

Example:

{
    "description": "Oasis were ...",
    "views": "1838795605",
    "name": "Oasis",
    "channelId": "UCUDVBtnOQi4c7E8jebpjc9Q",
    "subscribers": "2.3M",
    "subscribed": false,
    "thumbnails": [...],
    "songs": {
        "browseId": "VLPLMpM3Z0118S42R1npOhcjoakLIv1aqnS1",
        "results": [
            {
                "videoId": "ZrOKjDZOtkA",
                "title": "Wonderwall (Remastered)",
                "thumbnails": [...],
                "artist": "Oasis",
                "album": "(What's The Story) Morning Glory? (Remastered)"
            }
        ]
    },
    "albums": {
        "results": [
            {
                "title": "Familiar To Millions",
                "thumbnails": [...],
                "year": "2018",
                "browseId": "MPREb_AYetWMZunqA"
            }
        ],
        "browseId": "UCmMUZbaYdNH0bEd1PAlAqsA",
        "params": "6gPTAUNwc0JDbndLYlFBQV..."
    },
    "singles": {
        "results": [
            {
                "title": "Stand By Me (Mustique Demo)",
                "thumbnails": [...],
                "year": "2016",
                "browseId": "MPREb_7MPKLhibN5G"
            }
        ],
        "browseId": "UCmMUZbaYdNH0bEd1PAlAqsA",
        "params": "6gPTAUNwc0JDbndLYlFBQV..."
    },
    "videos": {
        "results": [
            {
                "title": "Wonderwall",
                "thumbnails": [...],
                "views": "358M",
                "videoId": "bx1Bh8ZvH84",
                "playlistId": "PLMpM3Z0118S5xuNckw1HUcj1D021AnMEB"
            }
        ],
        "browseId": "VLPLMpM3Z0118S5xuNckw1HUcj1D021AnMEB"
    }
}
YTMusic.get_artist_albums(channelId: str, params: str) → List[Dict[KT, VT]]

Get the full list of an artist’s albums or singles

Parameters:
  • channelId – channel Id of the artist
  • params – params obtained by get_artist()
Returns:

List of albums in the format of get_library_albums(), except artists key is missing.

YTMusic.get_user(channelId: str) → Dict[KT, VT]

Retrieve a user’s page. A user may own videos or playlists.

Parameters:channelId – channelId of the user
Returns:Dictionary with information about a user.

Example:

{
  "name": "4Tune – No Copyright Music",
  "videos": {
    "browseId": "UC44hbeRoCZVVMVg5z0FfIww",
    "results": [
      {
        "title": "Epic Music Soundtracks 2019",
        "videoId": "bJonJjgS2mM",
        "playlistId": "RDAMVMbJonJjgS2mM",
        "thumbnails": [
          {
            "url": "https://i.ytimg.com/vi/bJon...",
            "width": 800,
            "height": 450
          }
        ],
        "views": "19K"
      }
    ]
  },
  "playlists": {
    "browseId": "UC44hbeRoCZVVMVg5z0FfIww",
    "results": [
      {
        "title": "♚ Machinimasound | Playlist",
        "playlistId": "PLRm766YvPiO9ZqkBuEzSTt6Bk4eWIr3gB",
        "thumbnails": [
          {
            "url": "https://i.ytimg.com/vi/...",
            "width": 400,
            "height": 225
          }
        ]
      }
    ],
    "params": "6gO3AUNvWU..."
  }
}
YTMusic.get_user_playlists(channelId: str, params: str) → List[Dict[KT, VT]]

Retrieve a list of playlists for a given user. Call this function again with the returned params to get the full list.

Parameters:
  • channelId – channelId of the user.
  • params – params obtained by get_artist()
Returns:

List of user playlists in the format of get_library_playlists()

YTMusic.get_album(browseId: str) → Dict[KT, VT]

Get information and tracks of an album

Parameters:browseId – browseId of the album, for example returned by search()
Returns:Dictionary with title, description, artist and tracks.

Each track is in the following format:

{
  "title": "Seven",
  "trackCount": "7",
  "durationMs": "1439579",
  "playlistId": "OLAK5uy_kGnhwT08mQMGw8fArBowdtlew3DpgUt9c",
  "releaseDate": {
    "year": 2016,
    "month": 10,
    "day": 28
  },
  "description": "Seven is ...",
  "thumbnails": [...],
  "artist": [
    {
      "name": "Martin Garrix",
      "id": "UCqJnSdHjKtfsrHi9aI-9d3g"
    }
  ],
  "tracks": [
    {
      "index": "1",
      "title": "WIEE (feat. Mesto)",
      "artists": "Martin Garrix",
      "videoId": "8xMNeXI9wxI",
      "lengthMs": "203406",
      "likeStatus": "INDIFFERENT"
    }
  ]
}
YTMusic.get_song(videoId: str) → Dict[KT, VT]

Returns metadata about a song or video.

Parameters:videoId – Video id
Returns:Dictionary with song metadata.

Example:

{
  "videoId": "ZrOKjDZOtkA",
  "title": "Wonderwall (Remastered)",
  "lengthSeconds": "259",
  "keywords": [
    "Oasis",
    "(What's",
    "..."
  ],
  "channelId": "UCmMUZbaYdNH0bEd1PAlAqsA",
  "isOwnerViewing": false,
  "shortDescription": "Provided to YouTube by Ignition...",
  "isCrawlable": true,
  "thumbnail": {
    "thumbnails": [
      {
        "url": "https://i.ytimg.com/vi/ZrOKjDZOtkA/maxresdefault.jpg",
        "width": 1920,
        "height": 1080
      }
    ]
  },
  "averageRating": 4.5673099,
  "allowRatings": true,
  "viewCount": "18136380",
  "author": "Oasis - Topic",
  "isPrivate": false,
  "isUnpluggedCorpus": false,
  "isLiveContent": false,
  "provider": "Ignition",
  "artists": [
    "Oasis"
  ],
  "copyright": "℗ 2014 Big Brother Recordings ...",
  "production": [
    "Composer: Noel Gallagher",
    "Lyricist: Noel Gallagher",
    "Producer: Owen Morris & Noel Gallagher"
  ],
  "release": "2014-09-29"
  "category": "Music"
}
YTMusic.get_streaming_data(videoId: str) → Dict[KT, VT]

Returns the streaming data for a song or video.

Parameters:videoId – Video id
Returns:Dictionary with song streaming data.

Example:

{
    "expiresInSeconds": "21540",
    "formats": [
        {
            "itag": 18,
            "mimeType": "video/mp4; codecs="avc1.42001E, mp4a.40.2"",
            "bitrate": 306477,
            "width": 360,
            "height": 360,
            "lastModified": "1574970034520502",
            "contentLength": "9913027",
            "quality": "medium",
            "fps": 25,
            "qualityLabel": "360p",
            "projectionType": "RECTANGULAR",
            "averageBitrate": 306419,
            "audioQuality": "AUDIO_QUALITY_LOW",
            "approxDurationMs": "258809",
            "audioSampleRate": "44100",
            "audioChannels": 2,
            "signatureCipher": "s=..."
        }
    ],
    "adaptiveFormats": [
        {
            "itag": 137,
            "mimeType": "video/mp4; codecs="avc1.640020"",
            "bitrate": 312234,
            "width": 1078,
            "height": 1080,
            "initRange": {
                "start": "0",
                "end": "738"
            },
            "indexRange": {
                "start": "739",
                "end": "1382"
            },
            "lastModified": "1574970033536914",
            "contentLength": "5674377",
            "quality": "hd1080",
            "fps": 25,
            "qualityLabel": "1080p",
            "projectionType": "RECTANGULAR",
            "averageBitrate": 175432,
            "approxDurationMs": "258760",
            "signatureCipher": "s=..."
        },
        {...},
        {
            "itag": 140,
            "mimeType": "audio/mp4; codecs="mp4a.40.2"",
            "bitrate": 131205,
            "initRange": {
                "start": "0",
                "end": "667"
            },
            "indexRange": {
                "start": "668",
                "end": "1011"
            },
            "lastModified": "1574969975805792",
            "contentLength": "4189579",
            "quality": "tiny",
            "projectionType": "RECTANGULAR",
            "averageBitrate": 129521,
            "highReplication": true,
            "audioQuality": "AUDIO_QUALITY_MEDIUM",
            "approxDurationMs": "258773",
            "audioSampleRate": "44100",
            "audioChannels": 2,
            "loudnessDb": 1.1422243,
            "signatureCipher": "s=..."
        },
        {...}
    ]
}
YTMusic.get_lyrics(browseId: str) → Dict[KT, VT]

Returns lyrics of a song or video.

Parameters:browseId – Lyrics browse id obtained from get_watch_playlist
Returns:Dictionary with song lyrics.

Example:

{
    "lyrics": "Today is gonna be the day\nThat they're gonna throw it back to you\n",
    "source": "Source: LyricFind"
}

Watch

YTMusic.get_watch_playlist(videoId: str = None, playlistId: str = None, limit=25, params: str = None) → Dict[List[Dict[KT, VT]], str]

Get a watch list of tracks. This watch playlist appears when you press play on a track in YouTube Music.

Please note that the INDIFFERENT likeStatus of tracks returned by this endpoint may be either INDIFFERENT or DISLIKE, due to ambiguous data returned by YouTube Music.

Parameters:
  • videoId – videoId of the played video
  • playlistId – playlistId of the played playlist or album
  • limit – minimum number of watch playlist items to return
  • params – only used internally by get_watch_playlist_shuffle()
Returns:

List of watch playlist items.

Example:

{
    "tracks": [
        {
          "title": "Interstellar (Main Theme) - Piano Version",
          "byline": "Patrik Pietschmann • 47M views",
          "length": "4:47",
          "videoId": "4y33h81phKU",
          "playlistId": "RDAMVM4y33h81phKU",
          "thumbnail": [
            {
              "url": "https://i.ytimg.com/vi/4y...",
              "width": 400,
              "height": 225
            }
          ],
          "feedbackTokens": [],
          "likeStatus": "LIKE"
        },...
    ],
    "lyrics": "MPLYt_HNNclO0Ddoc-17"
}
YTMusic.get_watch_playlist_shuffle(playlistId: str = None, limit=50) → Dict[List[Dict[KT, VT]], str]

Shuffle any playlist

Parameters:
  • playlistId – Playlist id
  • limit – The number of watch playlist items to return
Returns:

A list of watch playlist items (see get_watch_playlist())

Library

YTMusic.get_library_playlists(limit: int = 25) → List[Dict[KT, VT]]

Retrieves the playlists in the user’s library.

Parameters:limit – Number of playlists to retrieve
Returns:List of owned playlists.

Each item is in the following format:

{
    'playlistId': 'PLQwVIlKxHM6rz0fDJVv_0UlXGEWf-bFys',
    'title': 'Playlist title',
    'thumbnails: [...],
    'count': 5
}
YTMusic.get_library_songs(limit: int = 25, validate_responses: bool = False, order: str = None) → List[Dict[KT, VT]]

Gets the songs in the user’s library (liked videos are not included). To get liked songs and videos, use get_liked_songs()

Parameters:
  • limit – Number of songs to retrieve
  • validate_responses – Flag indicating if responses from YTM should be validated and retried in case when some songs are missing. Default: False
  • order – Order of songs to return. Allowed values: ‘a_to_z’, ‘z_to_a’, ‘recently_added’. Default: Default order.
Returns:

List of songs. Same format as get_playlist()

YTMusic.get_library_artists(limit: int = 25, order: str = None) → List[Dict[KT, VT]]

Gets the artists of the songs in the user’s library.

Parameters:
  • limit – Number of artists to return
  • order – Order of artists to return. Allowed values: ‘a_to_z’, ‘z_to_a’, ‘recently_added’. Default: Default order.
Returns:

List of artists.

Each item is in the following format:

{
  "browseId": "UCxEqaQWosMHaTih-tgzDqug",
  "artist": "WildVibes",
  "subscribers": "2.91K",
  "thumbnails": [...]
}
YTMusic.get_library_albums(limit: int = 25, order: str = None) → List[Dict[KT, VT]]

Gets the albums in the user’s library.

Parameters:
  • limit – Number of albums to return
  • order – Order of albums to return. Allowed values: ‘a_to_z’, ‘z_to_a’, ‘recently_added’. Default: Default order.
Returns:

List of albums.

Each item is in the following format:

{
  "browseId": "MPREb_G8AiyN7RvFg",
  "title": "Beautiful",
  "type": "Album",
  "thumbnails": [...],
  "artists": {
    "name": "Project 46",
    "id": "UCXFv36m62USAN5rnVct9B4g"
  },
  "year": "2015"
}
YTMusic.get_liked_songs(limit: int = 100) → Dict[KT, VT]

Gets playlist items for the ‘Liked Songs’ playlist

Parameters:limit – How many items to return. Default: 100
Returns:List of playlistItem dictionaries. See get_playlist()
YTMusic.get_history() → List[Dict[KT, VT]]

Gets your play history in reverse chronological order

Returns:List of playlistItems, see get_playlist() The additional property played indicates when the playlistItem was played The additional property feedbackToken can be used to remove items with remove_history_items()
YTMusic.remove_history_items(feedbackTokens: List[str]) → Dict[KT, VT]

Remove an item from the account’s history. This method does currently not work with brand accounts

Parameters:feedbackTokens – Token to identify the item to remove, obtained from get_history()
Returns:Full response
YTMusic.rate_song(videoId: str, rating: str = 'INDIFFERENT') → Dict[KT, VT]

Rates a song (“thumbs up”/”thumbs down” interactions on YouTube Music)

Parameters:
  • videoId – Video id
  • rating

    One of ‘LIKE’, ‘DISLIKE’, ‘INDIFFERENT’

    ’INDIFFERENT’ removes the previous rating and assigns no rating
Returns:

Full response

YTMusic.edit_song_library_status(feedbackTokens: List[str] = None) → Dict[KT, VT]

Adds or removes a song from your library depending on the token provided.

Parameters:feedbackTokens – List of feedbackTokens obtained from authenticated requests to endpoints that return songs (i.e. get_album())
Returns:Full response
YTMusic.rate_playlist(playlistId: str, rating: str = 'INDIFFERENT') → Dict[KT, VT]

Rates a playlist/album (“Add to library”/”Remove from library” interactions on YouTube Music) You can also dislike a playlist/album, which has an effect on your recommendations

Parameters:
  • playlistId – Playlist id
  • rating

    One of ‘LIKE’, ‘DISLIKE’, ‘INDIFFERENT’

    ’INDIFFERENT’ removes the playlist/album from the library
Returns:

Full response

YTMusic.subscribe_artists(channelIds: List[str]) → Dict[KT, VT]

Subscribe to artists. Adds the artists to your library

Parameters:channelIds – Artist channel ids
Returns:Full response
YTMusic.unsubscribe_artists(channelIds: List[str]) → Dict[KT, VT]

Unsubscribe from artists. Removes the artists from your library

Parameters:channelIds – Artist channel ids
Returns:Full response

Playlists

YTMusic.get_playlist(playlistId: str, limit: int = 100) → Dict[KT, VT]

Returns a list of playlist items

Parameters:
  • playlistId – Playlist id
  • limit – How many songs to return. Default: 100
Returns:

Dictionary with information about the playlist. The key tracks contains a List of playlistItem dictionaries

Each item is in the following format:

{
  "id": "PLQwVIlKxHM6qv-o99iX9R85og7IzF9YS_",
  "privacy": "PUBLIC",
  "title": "New EDM This Week 03/13/2020",
  "thumbnails": [...]
  "description": "Weekly r/EDM new release roundup. Created with github.com/sigma67/spotifyplaylist_to_gmusic",
  "author": "sigmatics",
  "year": "2020",
  "duration": "6+ hours",
  "trackCount": 237,
  "tracks": [
    {
      "videoId": "bjGppZKiuFE",
      "title": "Lost",
      "artists": [
        {
          "name": "Guest Who",
          "id": "UCkgCRdnnqWnUeIH7EIc3dBg"
        },
        {
          "name": "Kate Wild",
          "id": "UCwR2l3JfJbvB6aq0RnnJfWg"
        }
      ],
      "album": {
        "name": "Lost",
        "id": "MPREb_PxmzvDuqOnC"
      },
      "duration": "2:58",
      "likeStatus": "INDIFFERENT",
      "thumbnails": [...],
      "isAvailable": True,
      "isExplicit": False,
      "feedbackTokens": {
        "add": "AB9zfpJxtvrU...",
        "remove": "AB9zfpKTyZ..."
    }
  ]
}

The setVideoId is the unique id of this playlist item and needed for moving/removing playlist items

YTMusic.create_playlist(title: str, description: str, privacy_status: str = 'PRIVATE', video_ids: List[T] = None, source_playlist: str = None) → Union[str, Dict[KT, VT]]

Creates a new empty playlist and returns its id.

Parameters:
  • title – Playlist title
  • description – Playlist description
  • privacy_status – Playlists can be ‘PUBLIC’, ‘PRIVATE’, or ‘UNLISTED’. Default: ‘PRIVATE’
  • video_ids – IDs of songs to create the playlist with
  • source_playlist – Another playlist whose songs should be added to the new playlist
Returns:

ID of the YouTube playlist or full response if there was an error

YTMusic.edit_playlist(playlistId: str, title: str = None, description: str = None, privacyStatus: str = None, moveItem: Tuple[str, str] = None, addPlaylistId: str = None) → Union[str, Dict[KT, VT]]

Edit title, description or privacyStatus of a playlist. You may also move an item within a playlist or append another playlist to this playlist.

Parameters:
  • playlistId – Playlist id
  • title – Optional. New title for the playlist
  • description – Optional. New description for the playlist
  • privacyStatus – Optional. New privacy status for the playlist
  • moveItem – Optional. Move one item before another. Items are specified by setVideoId, see get_playlist()
  • addPlaylistId – Optional. Id of another playlist to add to this playlist
Returns:

Status String or full response

YTMusic.delete_playlist(playlistId: str) → Union[str, Dict[KT, VT]]

Delete a playlist.

Parameters:playlistId – Playlist id
Returns:Status String or full response
YTMusic.add_playlist_items(playlistId: str, videoIds: List[str], source_playlist: str = None, duplicates: bool = False) → Union[str, Dict[KT, VT]]

Add songs to an existing playlist

Parameters:
  • playlistId – Playlist id
  • videoIds – List of Video ids
  • source_playlist – Playlist id of a playlist to add to the current playlist (no duplicate check)
  • duplicates – If True, duplicates will be added. If False, an error will be returned if there are duplicates (no items are added to the playlist)
Returns:

Status String or full response

YTMusic.remove_playlist_items(playlistId: str, videos: List[Dict[KT, VT]]) → Union[str, Dict[KT, VT]]

Remove songs from an existing playlist

Parameters:
  • playlistId – Playlist id
  • videos – List of PlaylistItems, see get_playlist(). Must contain videoId and setVideoId
Returns:

Status String or full response

Uploads

YTMusic.get_library_upload_songs(limit: int = 25, order: str = None) → List[Dict[KT, VT]]

Returns a list of uploaded songs

Parameters:
  • limit – How many songs to return. Default: 25
  • order – Order of songs to return. Allowed values: ‘a_to_z’, ‘z_to_a’, ‘recently_added’. Default: Default order.
Returns:

List of uploaded songs.

Each item is in the following format:

{
  "entityId": "t_po_CICr2crg7OWpchDpjPjrBA",
  "videoId": "Uise6RPKoek",
  "artist": "Coldplay",
  "title": "A Sky Full Of Stars",
  "album": "Ghost Stories",
  "likeStatus": "LIKE",
  "thumbnails": [...]
}
YTMusic.get_library_upload_artists(limit: int = 25, order: str = None) → List[Dict[KT, VT]]

Gets the artists of uploaded songs in the user’s library.

Parameters:
  • limit – Number of artists to return. Default: 25
  • order – Order of artists to return. Allowed values: ‘a_to_z’, ‘z_to_a’, ‘recently_added’. Default: Default order.
Returns:

List of artists as returned by get_library_artists()

YTMusic.get_library_upload_albums(limit: int = 25, order: str = None) → List[Dict[KT, VT]]

Gets the albums of uploaded songs in the user’s library.

Parameters:
  • limit – Number of albums to return. Default: 25
  • order – Order of albums to return. Allowed values: ‘a_to_z’, ‘z_to_a’, ‘recently_added’. Default: Default order.
Returns:

List of albums as returned by get_library_albums()

YTMusic.get_library_upload_artist(browseId: str, limit: int = 25) → List[Dict[KT, VT]]

Returns a list of uploaded tracks for the artist.

Parameters:
  • browseId – Browse id of the upload artist, i.e. from get_library_upload_songs()
  • limit – Number of songs to return (increments of 25).
Returns:

List of uploaded songs.

Example List:

[
  {
    "entityId": "t_po_CICr2crg7OWpchDKwoakAQ",
    "videoId": "Dtffhy8WJgw",
    "title": "Hold Me (Original Mix)",
    "artist": [
      {
        "name": "Jakko",
        "id": "FEmusic_library_privately_owned_artist_detaila_po_CICr2crg7OWpchIFamFra28"
      }
    ],
    "album": null,
    "likeStatus": "LIKE",
    "thumbnails": [...]
  }
]
YTMusic.get_library_upload_album(browseId: str) → Dict[KT, VT]

Get information and tracks of an album associated with uploaded tracks

Parameters:browseId – Browse id of the upload album, i.e. from i.e. from get_library_upload_songs()
Returns:Dictionary with title, description, artist and tracks.

Example album:

{
  "title": "Hard To Stop - Single",
  "thumbnails": [...]
  "year": "2013",
  "trackCount": 1,
  "duration": "4 minutes, 2 seconds",
  "tracks": [
    {
      "entityId": "t_po_CICr2crg7OWpchDN6tnYBw",
      "videoId": "VBQVcjJM7ak",
      "title": "Hard To Stop (Vicetone x Ne-Yo x Daft Punk)",
      "likeStatus": "LIKE"
    }
  ]
}
YTMusic.upload_song(filepath: str) → Union[str, requests.models.Response]

Uploads a song to YouTube Music

Parameters:filepath – Path to the music file (mp3, m4a, wma, flac or ogg)
Returns:Status String or full response
YTMusic.delete_upload_entity(entityId: str) → Union[str, Dict[KT, VT]]

Deletes a previously uploaded song or album

Parameters:entityId – The entity id of the uploaded song or album, e.g. retrieved from get_library_upload_songs()
Returns:Status String or error