Search code examples
pythonyoutubeyoutube-apihttp-error

Catch "Video already in playlist." error in Youtube API (Python)


I'm using the youtube.playlistItems().insert function in a Python script. I know that some videos are already in the targeted playlist, which leads to an error

raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 409 when requesting https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&alt=json returned "Video already in playlist.">

How can I catch this error and just skip the video in question? I searched the insert help doc and the errors doc but could not find the appropriate attribute of my request to access (.error and .httperror did not work).

Thanks


Solution

  • You should be able to just catch the exception and continue like so:

    try:
        youtube.playlistItems().insert()
    except googleapiclient.errors.HttpError:
        pass
    

    I took a look at the API, and think it's worth considering the quota cost of insert(). The insert() method costs 50 and the list() method costs 1. Depending on the volume of requests, it may be wise to check the list of existing playlist items before attempting to insert a duplicate.

    current_items = youtube.playlistItems().list()
    if item_to_insert not in current_items:
        youtube.playlistItems().insert(item_to_insert)
    

    The value of this strategy depends entirely on the proportion of duplicates and your willingness to pay the API cost. Also, I'm not suggesting you call list() for each insertion, it would be better to call list() once and then batch the inserts, this is just a quick example.