YouTube Core Error Domain: Service Unavailable

Question:

I have a Python script that uses the YouTube API to add a video to a playlist that I created. Some of the time the function works, but other times, when I try to execute the request, I get this error message:
googleapiclient.errors.HttpError: <HttpError 409 when requesting https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet&alt=json returned "The operation was aborted.". Details: "[{'domain': 'youtube.CoreErrorDomain', 'reason': 'SERVICE_UNAVAILABLE'}]">
Why would it work only some of the time and most importantly, is it mine or YouTube’s fault? If it is my fault, how can I fix it? Here is the function that I call:

def addSongToPlaylist(self, video_id, playlist_id): # Adds a song to the playlist given
    request = add_video_request=self.youtube_service.playlistItems().insert(
    part="snippet",
    body={
            'snippet': {
                 playlistId': playlist_id, 
                 'resourceId': {
                    'kind': 'youtube#video',
                    'videoId': video_id
                }
            }
        }
    )
    print(video_id)
    response = request.execute()
    return response

I’ve also printed the video_id to make sure that it is a valid id and it always is. Thanks to anyone who can help 🙂

Asked By: Matthew

||

Answers:

The problem is on youtube sid, it might be temporarily unavailable, one solution would be to put a retry mechanism so that it can handle those service disturbance.
Here is how you could do it in your code:

import time
from googleapiclient.errors import HttpError

def addSongToPlaylist(self, video_id, playlist_id): # Adds a song to the playlist given
    max_retries = 5
    retry_count = 0
    backoff_time = 1  # In seconds

    while retry_count < max_retries:
        try:
            request = self.youtube_service.playlistItems().insert(
                part="snippet",
                body={
                    'snippet': {
                        'playlistId': playlist_id,
                        'resourceId': {
                            'kind': 'youtube#video',
                            'videoId': video_id
                        }
                    }
                }
            )
            print(video_id)
            response = request.execute()
            return response
        except HttpError as e:
            if e.resp.status == 409 and 'SERVICE_UNAVAILABLE' in str(e):
                retry_count += 1
                print(f"Attempt {retry_count} failed. Retrying in {backoff_time} seconds...")
                time.sleep(backoff_time)
                backoff_time *= 2  # Exponential backoff
            else:
                raise
    raise Exception("Failed to add the song to the playlist after multiple retries.")
Answered By: Saxtheowl