API Calls

class ayt_api.api.AsyncYoutubeAPI(yt_api_key: str = None, api_version: str = '3', timeout: float = 5, ignore_ssl: bool = False, session: OAuth2Session = None, oauth_token: str = None, use_oauth=False, oauth_token_type: str = 'Bearer')[source]

Bases: object

Represents the main class for running all the tools.

Added in version 0.4.0: Supports OAuth2 methods for running privileged api calls.

api_version

The API version to use. Defaults to 3.

Type:

str

call_url_prefix

The start of the YouTube API call url to use.

Type:

str

timeout

The timeout if the api does not respond.

Type:

aiohttp.ClientTimeout

ignore_ssl

Whether to ignore any verification errors with the ssl certificate. This is useful for using the api on a restricted network.

Type:

bool

quota_usage

The number of YouTube API quota that have units used this session.

Type:

int

Parameters:
  • yt_api_key (str) – The API key used to access the YouTube API. to get an API key. See instructions here: https://developers.google.com/youtube/v3/getting-started

  • api_version (str) – The API version to use. Defaults to 3.

  • timeout (float) – The timeout if the api does not respond.

  • ignore_ssl (bool) – Whether to ignore any verification errors with the ssl certificate. This is useful for using the api on a restricted network.

  • session (OAuth2Session) –

    The OAuth2 session used for authorised requests.

    Added in version 0.4.0.

  • oauth_token (str) –

    The OAuth token to used for authorised requests.

    Added in version 0.4.0.

  • use_oauth (bool) –

    Whether to use the oauth token over the api key.

    Added in version 0.4.0.

Raises:

NoAuth – no api key or OAuth2 token was provided. Added in version 0.4.0.

URL_PREFIX = 'https://www.googleapis.com/youtube/v{version}'
classmethod generate_url_and_socket(client_id: str, scopes: list[OAuth2Scope] = None) tuple[str, socket][source]

Sets up a consent url and a socket to use with oauth2 authentication.

Added in version 0.4.0.

Parameters:
Returns:

The consent url and internal socket to use later with

with_authcode_receiver().

Return type:

tuple[str, socket.socket]

Raises:

OSError – Setting up the socket failed

async classmethod with_authcode_receiver(oauth2_consent_url: str, sock: socket, client_secret: str, api_version: str = '3', timeout: float = 5, ignore_ssl: bool = False)[source]

Run the AsyncYoutubeAPI session by first setting up a web server to listen for a connection after the oauth2 consent is complete and receive the authentication code to then exchange for an oauth2 access token.

Added in version 0.4.0.

Parameters:
  • oauth2_consent_url (str) – The oauth2 consent url containing the client id and the redirect uri

  • sock (socket.socket) – The socket to listen on that the redirect uri leads to

  • client_secret (str) – The client secret as part of OAuth client credentials created at https://console.cloud.google.com/apis/credentials.

  • api_version (str) – The API version to use. Defaults to 3.

  • timeout (float) – The timeout if the api does not respond.

  • ignore_ssl (bool) – Whether to ignore any verification errors with the ssl certificate. This is useful for using the api on a restricted network.

Returns:

The instance of the main class that runs all the api calls

Return type:

AsyncYoutubeAPI

Raises:
classmethod with_oauth_flow_generator(client_id: str, client_secret: str, api_version: str = '3', timeout: float = 5, ignore_ssl: bool = False) AsyncGenerator[str | AsyncYoutubeAPI][source]

A generator that yields an OAuth consent url, waits for authorisation, and automatically requests an access token before yielding a AsyncYoutubeAPI object that has oauth2 credentials automatically provided.

Added in version 0.4.0.

An example of how to use:

api = None
async for stage in ayt_api.AsyncYoutubeAPI.with_oauth_flow_generator("Your Client ID", "Your Client Secret"):
    if isinstance(stage, str):
        # prints the oauth consent url
        print(stage)
        continue
    # stage is now an AscyncYoutubeAPI object that is assigned to api
    api = stage
if api:
    resource = await api.fetch_video("Video ID", authorised=True)
    print(resource.file_name)
Parameters:
Yields:

Union[str, AsyncYoutubeAPI]

The OAuth2 consent url and then the instance of the main class that runs all

the api calls

Raises:
async classmethod with_authorisation_code(code: str, client_id: str, client_secret: str, redirect_uri: str, api_version: str = '3', timeout: float = 5, ignore_ssl: bool = False)[source]

Run the AsyncYoutubeAPI session using OAuth 2 client credentials and an authorisation code received from an OAuth2 consent screen.

Added in version 0.4.0.

Parameters:
  • code (str) – The authorisation code received after completing an OAuth2 consent screen.

  • client_id (str) – A client id as part of OAuth client credentials created at https://console.cloud.google.com/apis/credentials.

  • client_secret (str) – The client secret as part of OAuth client credentials created at https://console.cloud.google.com/apis/credentials.

  • redirect_uri (str) – The URI that was sent after the OAuth consent screen was completed

  • api_version (str) – The API version to use. Defaults to 3.

  • timeout (float) – The timeout if the api does not respond.

  • ignore_ssl (bool) – Whether to ignore any verification errors with the ssl certificate. This is useful for using the api on a restricted network.

Returns:

The instance of the main class that runs all the api calls

Return type:

AsyncYoutubeAPI

Raises:
async refresh_session()[source]

Refresh the access token for the current OAuth2 Session

Added in version 0.4.0.

Note

This function is for refreshing the access_token if AsyncYoutubeAPI was initialised using one of the class-methods. If the class was not initialised in this way e.g. only providing an API key or just an OAuth2 access token by itself, running this function will raise NoSession.

Raises:
async download_thumbnail(thumbnail_url: str) bytes[source]

Downloads the thumbnail specified and stores it as a bytes object

Parameters:

thumbnail_url (str) – The i.ytimg.com asset url of the thumbnail

Returns:

The image as a bytes object

Return type:

bytes

Raises:
async save_thumbnail(thumbnail_url: str, fp: PathLike | str | None = None)[source]

Downloads the thumbnail specified and saves it to a specified location

Parameters:
  • thumbnail_url (str) – The i.ytimg.com asset url of the thumbnail

  • fp (Union[os.PathLike, str, None]) – The path and/or filename to save the file to. Defaults to current working directory with the filename format: {video_id}-{quality}.png

Raises:
async download_banner(banner_url: str) tuple[bytes, str][source]

Downloads the banner specified and stores it as a bytes object

Parameters:

banner_url (str) – The yt3.ggpht.com or yt3.googleusercontent.com asset url of the banner

Returns:

A list containing the image as a bytes object and the file extension of

the image

Return type:

tuple[bytes, str]

Raises:
async save_banner(banner_url: str, fp: PathLike | str | None = None)[source]

Downloads the banner specified and saves it to a specified location

Parameters:
  • banner_url (str) – The yt3.ggpht.com or yt3.googleusercontent.com asset url of the thumbnail

  • fp (Union[os.PathLike, str, None]) – The path and/or filename to save the file to. Defaults to current working directory with the filename format: {banner_id}.{extension}

Raises:
async download_caption(track_id: str, track_format: CaptionFormat | None = None, language: str | None = None) bytes[source]

Downloads the caption track from the ID specified and stores it as a bytes object

Added in version 0.4.0.

Quota Impact

A call to this method has a quota cost of 200 units per call.

Note

You must be the owner of the video of the captions and use OAuth authentication to call this method with one of the following scopes:

Parameters:
  • track_id (str) – The ID of the caption track

  • track_format (Optional[CaptionFormat]) – The format YouTube should return the captions in.

  • language (Optional[str]) – The alpha-2 language code to translate the caption track into.

Returns:

The caption track as a bytes object.

Return type:

bytes

Raises:
async save_caption(track_id: str, *, track_format: CaptionFormat | None = None, language: str | None = None, fp: PathLike | str | None = None)[source]

Downloads the caption track from the ID specified and saves it to a specified location

Added in version 0.4.0.

Quota Impact

A call to this method has a quota cost of 200 units per call.

Note

You must be the owner of the video of the captions and use OAuth authentication to call this method with one of the following scopes:

Parameters:
  • track_id (str) – The ID of the caption track

  • track_format (Optional[CaptionFormat]) – The format YouTube should return the captions in.

  • language (Optional[str]) – The alpha-2 language code to translate the caption track into.

  • fp (Union[os.PathLike, str, None]) – The path and/or filename to save the file to. Defaults to current working directory with the filename format: {track_id}.{file_extension (if any)}

Raises:
async fetch_playlist(playlist_id: str | list[str], ignore_not_found=False) YoutubePlaylist | list[YoutubePlaylist] | list[source]

Fetches playlist metadata using a playlist id.

Playlist metadata is fetched using a GET request which the response is then concentrated into a YoutubePlaylist object.

Quota Impact

A call to this method has a quota cost of 1 unit per call or per 50 playlists fetched.

Parameters:
  • playlist_id (str) – The id of the playlist to use. e.g. PLwZcI0zn-Jhc-H2CQvoqKvPuC8C9gClIF.

  • ignore_not_found (bool) –

    Ignore any playlists that were not returned by this method.

    Added in version 0.4.0.

Returns:

The playlist object containing data of the playlist.

Return type:

Union[YoutubePlaylist, list[YoutubePlaylist], list]

Raises:
async fetch_playlist_items(playlist_id: str, max_items=None) list[PlaylistItem][source]

Fetches a list of items in a playlist using a playlist id.

Playlist video metadata is fetched using a GET request which the response is then concentrated into a list of PlaylistItem objects.

Quota Impact

A call to this method has a quota cost of 1 unit per call or per 50 items fetched.

Parameters:
  • playlist_id (str) – The id of the playlist to use. e.g. PLwZcI0zn-Jhc-H2CQvoqKvPuC8C9gClIF.

  • max_items (int | None) –

    The maximum number of playlist items to fetch. Defaults to None which fetches every item in a playlist.

    Added in version 0.4.0.

    Warning

    If a specified playlist has a lot of videos, not specifying a value to max_items could hammer the api too much causing you to get rate limited so do this with caution.

Returns:

A list containing playlist video objects.

Return type:

list[PlaylistItem]

Raises:
async fetch_playlist_videos(playlist_id, exclude: list[str] = None, ignore_not_found=False) list[YoutubeVideo] | list[source]

Fetches a list of videos in a playlist using a playlist id.

Playlist videos are fetched using a GET request which the response is then concentrated into a list of YoutubeVideo objects.

Quota Impact

A call to this method has a quota cost of 2 units per call or per 50 videos fetched.

Parameters:
  • playlist_id (str) – The id of the playlist to use. e.g. PLwZcI0zn-Jhc-H2CQvoqKvPuC8C9gClIF.

  • exclude (Optional[list[str]]) –

    A list of videos to not fetch in the playlist.

    Deprecated since version 0.4.0: Use ignore_not_found instead.

  • ignore_not_found (bool) –

    Ignore any videos that were not returned by this method.

    Added in version 0.4.0.

Returns:

A list containing playlist video objects.

Return type:

Union[list[YoutubeVideo], list]

Raises:
async fetch_video(video_id: str | list[str], authorised=False, ignore_not_found=False) YoutubeVideo | list[YoutubeVideo] | AuthorisedYoutubeVideo | list[AuthorisedYoutubeVideo] | list[source]

Fetches information on a video using a video id.

Video metadata is fetched using a GET request which the response is then concentrated into a YoutubeVideo object if one ID was specified if more, it returns a list of them.

Quota Impact

A call to this method has a quota cost of 1 unit per call or per 50 videos fetched.

Parameters:
  • video_id (str) – The id of the video to use. e.g. dQw4w9WgXcQ. Look familiar?

  • authorised (bool) –

    Whether to fetch additional uploader side information about a video (Needs OAuth token).

    Added in version 0.4.0.

  • ignore_not_found (bool) –

    Ignore any videos that were not returned by this method.

    Added in version 0.4.0.

Returns:

The video object containing data of the video.

Changed in version 0.4.0: Now could also return a AuthorisedYoutubeVideo as well

Return type:

Union[YoutubeVideo, list[YoutubeVideo], AuthorisedYoutubeVideo, list[AuthorisedYoutubeVideo], list]

Raises:
async fetch_channel(channel_id: str | list[str], ignore_not_found=False) YoutubeChannel | list[YoutubeChannel] | list[source]

Fetches information on a channel using a channel id.

Channel metadata is fetched using a GET request which the response is then concentrated into a YoutubeChannel object or a list if multiple IDs were specified.

Quota Impact

A call to this method has a quota cost of 1 unit per call or per 50 channels fetched.

Parameters:
  • channel_id (str) – The id of the channel to use. e.g. UC1VSDiiRQZRTbxNvWhIrJfw.

  • ignore_not_found (bool) –

    Ignore any channels that were not returned by this method.

    Added in version 0.4.0.

Returns:

The channel object containing data of the channel.

Return type:

Union[YoutubeChannel, list[YoutubeChannel], list]

Raises:
async fetch_channel_from_handle(handle: str | list[str], ignore_not_found=False) YoutubeChannel | list[YoutubeChannel] | list[source]

Fetches information on a channel using a channel’s handle.

Channel metadata is fetched using a GET request which the response is then concentrated into a YoutubeChannel object or a list if multiple IDs were specified.

Quota Impact

A call to this method has a quota cost of 1 unit per call or per 50 channels fetched.

Added in version 0.4.0.

Parameters:
  • handle (str) – The handle of the channel to use. e.g. @Revnoplex.

  • ignore_not_found (bool) – Ignore any channels that were not returned by this method.

Returns:

The channel object containing data of the channel.

Return type:

Union[YoutubeChannel, list[YoutubeChannel], list]

Raises:
async fetch_video_comments(video_id: str, max_comments: int | None = 50) list[YoutubeCommentThread][source]

Fetches comments on a video.

A list of comment threads are fetched using a GET request which the response is then concentrated into a YoutubeCommentThread object.

Quota Impact

A call to this method has a quota cost of 1 unit per call or per 50 comments fetched.

Parameters:
  • video_id (str) – The id of the video to use. e.g. dQw4w9WgXcQ. Look familiar?

  • max_comments (int) –

    The maximum number of comments to fetch. Specify None to fetch all comments.

    Warning

    Specifying a high number or None could hammer the api too much causing you to get rate limited so do this with caution.

Returns:

A list of comments as YoutubeCommentThread.

Return type:

list[YoutubeCommentThread]

Raises:
async fetch_channel_comments(channel_id: str, max_comments: int | None = 50) list[YoutubeCommentThread][source]

Fetches comments on an entire channel.

A list of comment threads are fetched using a GET request which the response is then concentrated into a YoutubeCommentThread object.

Quota Impact

A call to this method has a quota cost of 1 unit per call or per 50 comments fetched.

Parameters:
  • channel_id (str) – The id of the channel to use. e.g. UC1VSDiiRQZRTbxNvWhIrJfw.

  • max_comments (int) –

    The maximum number of comments to fetch. Specify None to fetch all comments.

    Warning

    Specifying a high number or None could hammer the api too much causing you to get rate limited so do this with caution.

Returns:

A list of comments as YoutubeCommentThread.

Return type:

list[YoutubeCommentThread]

Raises:
async fetch_comment(comment_id: str | list[str], ignore_not_found=False) YoutubeComment | list[YoutubeComment] | list[source]

Fetches individual comments.

comments are fetched using a GET request which the response is then concentrated into a YoutubeComment object or a list if a list of ids were specified.

Quota Impact

A call to this method has a quota cost of 1 unit per call or per 50 comments fetched.

Parameters:
  • comment_id (str) – The id of the comment to use. e.g. UgzuC3zzpRZkjc5Qzsd4AaABAg.

  • ignore_not_found (bool) –

    Ignore any comments that were not returned by this method.

    Added in version 0.4.0.

Returns:

The YouTube comment object.

Return type:

Union[YoutubeComment, list[YoutubeComment], list]

Raises:
async fetch_comment_replies(comment_id: str, max_comments: int | None = 50) list[YoutubeComment][source]

Fetches a list of replies on a comment.

comments are fetched using a GET request which the response is then concentrated into a list[YoutubeComment] object.

Quota Impact

A call to this method has a quota cost of 1 unit per call or per 50 comments fetched.

Parameters:
  • comment_id (str) – The id of the comment to use. e.g. UgzuC3zzpRZkjc5Qzsd4AaABAg.

  • max_comments (int) –

    The maximum number of comments to fetch. Specify None to fetch all comments.

    Warning

    Specifying a high number or None could hammer the api too much causing you to get rate limited so do this with caution.

Returns:

The replies on the comment.

Return type:

list[YoutubeComment]

Raises:
async search(query: str, max_results=10, search_filter: SearchFilter = None) list[YoutubeSearchResult][source]

Sends a search request to the api and returns a list of videos and/or channels and/or playlists depending on the query provided and the filters used.

Quota Impact

A call to this method has a quota cost of 100 units per call or per 50 results fetched.

Parameters:
  • query (str) – The keywords to search for

  • max_results (int) – The maximum number of results to fetch. Defaults to 10

  • search_filter (Optional[SearchFilter]) – An object containing the filters active in the search

Returns:

A list of videos/channels/playlists returned by the search.

Return type:

list[YoutubeSearchResult]

Raises:
async fetch_video_captions(video_id: str) list[VideoCaption][source]

Fetches captions on a video.

A list of available captions are fetched using a GET request which the response is then concentrated into a list[VideoCaptions] object.

Quota Impact

A call to this method has a quota cost of 50 units per call or per 50 captions fetched.

Parameters:

video_id (str) – The id of the video to use. e.g. dQw4w9WgXcQ. Look familiar?

Returns:

A list of captions as VideoCaption.

Return type:

list[VideoCaption]

Raises:
async resolve_handle(username: str) str[source]

Resolve a channel’s handle name into a channel id.

Quota Impact

A call to this method has a quota cost of 1 unit per call.

Added in version 0.4.0.

Parameters:

username (str) – The handle name of the channel to resolve. e.g. @Revnoplex.

Returns:

The ID of the channel. e.g. UC1VSDiiRQZRTbxNvWhIrJfw.

Return type:

str

Raises:
async fetch_subscriptions(channel_id: str, max_items: int = 50) list[YoutubeSubscription][source]

Fetch subscriptions a specified channel has

Quota Impact

A call to this method has a quota cost of 1 unit per call or per 50 subscriptions fetched.

Added in version 0.4.0.

Parameters:
  • channel_id (str) – The ID of the channel to fetch the subscriptions of. e.g. UC1VSDiiRQZRTbxNvWhIrJfw.

  • max_items (int) –

    The maximum number of subscriptions to fetch. Defaults to 50. Specify None to fetch all comments.

    Warning

    Specifying a high number or None could hammer the api too much causing you to get rate limited so do this with caution.

Returns:

A list of the channel’s subscriptions as YoutubeSubscription

Return type:

list[YoutubeSubscription]

Raises:
async fetch_video_category(category_id: str | list[str], ignore_not_found=False) YoutubeVideoCategory | list[YoutubeVideoCategory] | list[source]

Fetches a category that has been or could be associated with uploaded videos.

Quota Impact

A call to this method has a quota cost of 1 unit per call or per 50 categories fetched.

Added in version 0.4.0.

Parameters:
  • category_id (Union[str, list[str], list]) – The video category ID/s to fetch.

  • ignore_not_found (bool) – Ignore any categories that were not returned by this method.

Returns:

The video category/ies

Return type:

Union[YoutubeVideoCategory, list[YoutubeVideoCategory]]

Raises:
async fetch_youtube_regions(language: str = None) dict[str, str][source]

Fetches a dictionary containing the names of regions listed by YouTube

Quota Impact

A call to this method has a quota cost of 1 unit per call or per 50 regions fetched.

Added in version 0.4.0.

Parameters:

language (str) – The BCP-47 language code to return the results in

Returns:

A dictionary containing ISO 3166-1 alpha-2 codes mapped to their names listed by YouTube

Return type:

dict[str, str]

Raises:
async fetch_youtube_languages(language: str) dict[str, str][source]

Fetches a dictionary containing the names of languages listed by YouTube

Quota Impact

A call to this method has a quota cost of 1 unit per call or per 50 languages fetched.

Added in version 0.4.0.

Parameters:

language (str) – The BCP-47 language code to return the results in

Returns:

A dictionary containing BCP-47 language codes mapped to their names listed by YouTube

Return type:

dict[str, str]

Raises:
async update_video(video: AuthorisedYoutubeVideo | list[AuthorisedYoutubeVideo], *, title: str | EXISTING = EXISTING, category_id: str | EXISTING = EXISTING, default_language: str | EXISTING | None = EXISTING, description: str | EXISTING | None = EXISTING, tags: list[str] | EXISTING | None = EXISTING, embeddable: bool | EXISTING | None = EXISTING, video_license: License | EXISTING | None = EXISTING, visibility: PrivacyStatus | EXISTING | None = EXISTING, public_stats_viewable: bool | EXISTING | None = EXISTING, publish_at: datetime | EXISTING | None = EXISTING, made_for_kids: bool | EXISTING | None = EXISTING, contains_synthetic_media: bool | EXISTING | None = EXISTING, recording_date: datetime | EXISTING | None = EXISTING, localisations: list[LocalName] | EXISTING | None = EXISTING) AuthorisedYoutubeVideo | list[AuthorisedYoutubeVideo][source]

Updates metadata for a video.

Added in version 0.4.0.

Values default to a special constant called EXISTING which is from the class ayt_api.types.UseExisting. Specify any other value in order to edit the property you want.

Quota Impact

A call to this method has a quota cost of 50 units per call.

Important

Specifying None for a parameter will wipe it or set it to YouTube’s default value.

Note

This method requires OAuth2 authentication with at least the default scope.

Parameters:
  • video (Union[YoutubeVideo, list[YoutubeVideo]]) – The YouTube video instance to be updated.

  • title (Union[str, EXISTING]) –

    The title of the video to set.

    Note

    This value cannot be set to None or an empty string as YouTube forbids this.

  • category_id (Union[str, EXISTING]) –

    The category id to set for the video.

    Note

    This value cannot be set to None or an empty string as YouTube forbids this.

  • default_language (Union[str, EXISTING, None]) – The default language the video should be set in. The value should be a BCP-47 language code.

  • description (Union[str, EXISTING, None]) – The description of the video to set.

  • tags (Union[list[str], EXISTING, None]) – The tags the to set to make the video appear in search results relating to it.

  • embeddable (Union[bool, EXISTING, None]) – Set whether the video can be embedded on another website.

  • video_license (Union[License, EXISTING, None]) – The YouTube license to set for the video.

  • visibility (Union[PrivacyStatus, EXISTING, None]) – Set the video’s privacy status.

  • public_stats_viewable (Union[bool, EXISTING, None]) – Set whether the extended video statistics on the video’s watch page are publicly viewable.

  • publish_at (Union[datetime.datetime, EXISTING, None]) –

    Set the date and time when the video is scheduled to publish.

    Note

    If you set a value for this property, you must also set the visibility property to ayt_api.enums.PrivacyStatus.private.

  • made_for_kids (Union[bool, EXISTING, None]) – Designate the video as being child-directed.

  • contains_synthetic_media (Union[bool, EXISTING, None]) – Tell YouTube if the video contain realistic Altered or Synthetic (A/S) content.

  • recording_date (Union[datetime.datetime, EXISTING, None]) – Set the date and time when the video was recorded.

  • localisations (Union[list[LocalName], EXISTING, None]) – Specify translations of the video’s metadata.

Returns:

The updated video object.

Return type:

Union[AuthorisedYoutubeVideo, list[AuthorisedYoutubeVideo]]

Raises:
async set_video_thumbnail(video_id: str, image: bytes) YoutubeThumbnailMetadata[source]

Upload and set the thumbnail for a video.

Added in version 0.4.0.

Quota Impact

A call to this method has a quota cost of 50 units per call.

Note

This method requires OAuth2 authentication with at least the default scope.

Parameters:
  • video_id (str) – The ID of the video to set the thumbnail of.

  • image (bytes) – The thumbnail image to upload.

Returns:

The metadata of the uploaded thumbnail.

Return type:

YoutubeThumbnailMetadata

Raises:
async update_channel(channel: YoutubeChannel | list[YoutubeChannel], *, country: str | EXISTING | None = EXISTING, description: str | EXISTING | None = EXISTING, default_language: str | EXISTING | None = EXISTING, keywords: list[str] | EXISTING | None = EXISTING, tracking_analytics_account_id: str | EXISTING | None = EXISTING, unsubscribed_trailer: str | BaseVideo | EXISTING | None = EXISTING, localisations: list[LocalName] | EXISTING | None = EXISTING, made_for_kids: bool | EXISTING = EXISTING) YoutubeChannel | list[YoutubeChannel][source]

Updates metadata for a channel.

Added in version 0.4.0.

Values default to a special constant called EXISTING which is from the class ayt_api.types.UseExisting. Specify any other value in order to edit the property you want.

Quota Impact

A call to this method has a quota cost of between 0-150 units. As updating localisations and made_for_kids cost an extra 50 units each and not updating anything costs nothing as no API call is actually made.

Note

If no arguments after channel are specified or are all set to EXISTING, no API call is made and hence no quota units will be used. The function will just return the YoutubeChannel as it is.

Important

Specifying None for a parameter will wipe it or set it to YouTube’s default value.

Note

This method requires OAuth2 authentication with at least the default scope.

Parameters:
  • channel (Union[YoutubeVideo, list[YoutubeVideo]]) – The YouTube channel instance to be updated.

  • country (Union[str, EXISTING, None]) – The country to set which the channel is associated.

  • description (Union[str, EXISTING, None]) – The description of the channel to set.

  • default_language (Union[str, EXISTING, None]) – The default language the video should be set in. The value should be a BCP-47 language code.

  • keywords (Union[list[str], EXISTING, None]) – Keywords to set associated with your channel.

  • tracking_analytics_account_id (Union[str, EXISTING, None]) – The ID to set for a Google Analytics account used to track and measure traffic to the channel.

  • unsubscribed_trailer (Union[str, BaseVideo, EXISTING, None]) – The ID or BaseVideo to set of the video that should play in the featured video module in the channel page’s browse view for unsubscribed viewers.

  • localisations (Union[list[LocalName], EXISTING, None]) –

    Specify translations of the video’s metadata.

    Note

    This value cannot be set to None or an empty list as YouTube forbids this.

  • made_for_kids (Union[bool, EXISTING]) –

    Designate the channel as being child-directed.

    Note

    This value cannot be set to None as YouTube forbids this.

Returns:

The updated channel object.

Return type:

Union[YoutubeChannel, list[YoutubeChannel]]

Raises:
async set_channel_banner(channel: YoutubeChannel, image: bytes) tuple[YoutubeBanner, str][source]

Upload and set the banner for a channel.

Added in version 0.4.0.

Quota Impact

A call to this method has a quota cost of 100 units per call.

Note

This method requires OAuth2 authentication with at least the default scope.

Parameters:
  • channel (YoutubeChannel) – The channel to set the banner of.

  • image (bytes) –

    The banner image to upload.

    Note

    The image must have a 16:9 aspect ratio and be at least 2048x1152 pixels. YouTube recommends uploading a 2560px by 1440px image.

Returns:

The metadata of the uploaded banner and the etag of the updated YoutubeChannel instance.

Return type:

tuple[YoutubeBanner, str]

Raises:
async set_channel_watermark(channel_id: str, image: bytes, timing_type: WatermarkTimingType = None, timing_offset: timedelta = None, duration: timedelta = None)[source]

Upload and set the watermark for a channel.

Added in version 0.4.0.

Quota Impact

A call to this method has a quota cost of 50 units per call.

Note

This method requires OAuth2 authentication with at least the default scope.

Parameters:
  • channel_id (str) – The ID of the channel to set the watermark of.

  • image (bytes) – The watermark image to upload.

  • timing_type (Optional[WatermarkTimingType]) –

    The timing method that determines when the watermark image is displayed during the video playback.

    Note

    Setting this argument to None will make the watermark appear for the entire video.

  • timing_offset (Optional[datetime.timedelta]) – The time offset that determines when the promoted item appears during video playbacks. timing_type Determines if this offset if from the start or end of a video.

  • duration (Optional[datatime.timedelta]) – The length of time that the watermark image should display.

Raises:
async unset_channel_watermark(channel_id: str)[source]

Unset the watermark for a channel.

Added in version 0.4.0.

Quota Impact

A call to this method has a quota cost of 50 units per call.

Warning

If the channel currently has no watermark set, this function will raise WatermarkNotFound as the API throws a 404 error.

Note

This method requires OAuth2 authentication with at least the default scope.

Parameters:

channel_id (str) – The ID of the channel to unset the watermark of.

Raises:
async fetch_playlist_image_metadata(playlist_id: str) PlaylistImageMetadata | None[source]

Fetches metadata on custom playlist cover images if it has one.

Added in version 0.4.0.

Quota Impact

A call to this method has a quota cost of 1 unit per call.

Important

The API endpoint for playlist images is still in early stages and its own documentation currently has bits missing and contains a few errors and inconsistencies. Not everything may work as expected or may change and break this method.

Note

This method will not fetch the actual image asset due to YouTube limitations.

Parameters:

playlist_id (str) – The ID of the playlist to get the custom image information of.

Returns:

The metadata of the custom playlist image. Returns None if the playlist has no custom image set.

Return type:

Optional[PlaylistImageMetadata]

Raises:
async add_video_to_playlist(video: BaseVideo | str, playlist_id: str, *, position: int = None, note: str = None) PlaylistItem[source]

Add a video to a playlist.

Added in version 0.4.0.

Quota Impact

A call to this method has a quota cost of 50 units per call.

Note

This method requires OAuth2 authentication with at least the default scope.

Parameters:
  • video (Union[BaseVideo, str]) – The video or ID of the video to add to the playlist.

  • playlist_id (str) – The ID of the to add the video to.

  • position (Optional[int]) – The position in the playlist to add the video. Defaults to the end.

  • note (Optional[str]) –

    A user-generated note for this item. The note has a maximum character limit of 280 and the API is meant to throw a 400 error if this limit is exceeded.

    Important

    This property appears to be broken in this method as the API seems to ignore its value. Consider using update_playlist_item() if you want to set this value.

Returns:

The metadata for the item in the playlist related to the video.

Return type:

PlaylistItem

Raises:
  • HTTPException – Adding the video to the playlist failed or an invalid playlist position was set.

  • PlaylistNotFound – The playlist does not exist or is not accessible.

  • VideoNotFound – The video does not exist or is not accessible.

  • aiohttp.ClientError – There was a problem sending the request to the api.

  • InvalidInput – The input is not a playlist id.

  • APITimeout – The YouTube api did not respond within the timeout period set.

async update_playlist_item(item: PlaylistItem, *, position: int | EXISTING | None = EXISTING, note: str | EXISTING | None = EXISTING) PlaylistItem[source]

Update the metadata for the item.

Added in version 0.4.0.

Values default to a special constant called EXISTING which is from the class ayt_api.types.UseExisting. Specify any other value in order to edit the property you want.

Quota Impact

A call to this method has a quota cost of 50 units per call.

Important

Specifying None for a parameter will wipe it or set it to YouTube’s default value.

Note

This method requires OAuth2 authentication with at least the default scope.

Parameters:
  • item (PlaylistItem) – The playlist item to edit.

  • position (Union[int, EXISTING, None]) – The position in the playlist the item should be.

  • note (Union[str, EXISTING, None]) – A user-generated note for this item. The note has a maximum character limit of 280 and the API will throw a 400 error if this limit is exceeded.

Returns:

The updated metadata for the item in the playlist related to the video.

Return type:

PlaylistItem

Raises:
  • HTTPException – Editing the item in the playlist failed or an invalid playlist position or note was set.

  • ResourceNotFound – The playlist item does not exist or is not accessible.

  • aiohttp.ClientError – There was a problem sending the request to the api.

  • APITimeout – The YouTube api did not respond within the timeout period set.

async update_playlist(playlist: YoutubePlaylist, *, title: str | EXISTING = EXISTING, description: str | EXISTING | None = EXISTING, default_language: str | EXISTING | None = EXISTING, visibility: PrivacyStatus | EXISTING | None = EXISTING, podcast_status: PodcastStatus | EXISTING | None = EXISTING, localisations: list[LocalName] | EXISTING | None = EXISTING) YoutubePlaylist[source]

Updates metadata for a playlist.

Added in version 0.4.0.

Values default to a special constant called EXISTING which is from the class ayt_api.types.UseExisting. Specify any other value in order to edit the property you want.

Quota Impact

A call to this method has a quota cost of 50 units per call.

Important

Specifying None for a parameter will wipe it or set it to YouTube’s default value.

Note

This method requires OAuth2 authentication with at least the default scope.

Parameters:
  • playlist (YoutubePlaylist) – The YouTube video instance to be updated.

  • title (Union[str, EXISTING]) –

    The title of the playlist to set.

    Note

    This value cannot be set to None or an empty string as YouTube forbids this.

  • default_language (Union[str, EXISTING, None]) – The default language the playlist should be set in. The value should be a BCP-47 language code.

  • description (Union[str, EXISTING, None]) – The description of the playlist to set.

  • visibility (Union[PrivacyStatus, EXISTING, None]) – Set the playlist’s privacy status.

  • podcast_status (Union[PodcastStatus, EXISTING, None]) – Set the playlist’s podcast status.

  • localisations (Union[list[LocalName], EXISTING, None]) – Specify translations of the playlist’s metadata.

Returns:

The updated playlist object.

Return type:

YoutubePlaylist

Raises:
async fetch_playlists_from_channel(channel_id: str) list[YoutubePlaylist][source]

Fetches playlists created by a channel.

Added in version 0.4.0.

Quota Impact

A call to this method has a quota cost of 1 unit per call or per 50 playlists fetched.

Note

Only playlists marked as public will be returned if the request is made without OAuth2 authorisation using the associated channel.

Parameters:

channel_id (str) – The id of the channel to fetch the playlists related to

Returns:

The playlists created by the channel.

Return type:

list[YoutubePlaylist]

Raises:
async fetch_user_playlists() list[YoutubePlaylist][source]

Fetches playlists owned by the authenticated user.

Added in version 0.4.0.

Quota Impact

A call to this method has a quota cost of 1 unit per call or per 50 playlists fetched.

Note

This method requires OAuth2 authentication with at least the default scope.

Returns:

The playlists owned by the authenticated user.

Return type:

list[YoutubePlaylist]

Raises:
  • HTTPException – Fetching the metadata failed or this method was run without OAuth2 authentication.

  • ChannelNotFound – There the authenticated user does not have a channel.

  • aiohttp.ClientError – There was a problem sending the request to the api.

  • APITimeout – The YouTube api did not respond within the timeout period set.

async fetch_user_channel() YoutubeChannel[source]

Fetches the channel owned by the authenticated user.

Added in version 0.4.0.

Quota Impact

A call to this method has a quota cost of 1 unit per call.

Note

This method requires OAuth2 authentication with at least the default scope.

Returns:

The channel owned by the authenticated user.

Return type:

YoutubeChannel

Raises: