Search code examples
pythonloopsyoutubeyoutube-apiplaylist

Adding multiple videos to youtube-playlist via API (Python)


I'm having troubles adding multiple videos to an already existing playlist on YouTube.

Currently, I can add multiple videos by repeating a fragment of code (the bit from request = to print(f"\n{response}")) with different video IDs over and over again in my script ; but, I' like to find a smarter and better way to do that.

I already tried to read other posts regarding this problem, but unfortunately, they did not work for me.

Also, I checked the Google YouTube API documentation but I could not find a solution for my problem over there.

Since this is my first post, please let me know if I need to add more information for the community to solve the problem.

This is the code I'm currently working with :

# -*- coding: utf-8 -*-

# Sample Python code for youtube.playlistItems.insert
# See instructions for running these code samples locally:
# https://developers.google.com/explorer-help/guides/code_samples#python

import os

import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors

scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]

def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = "XXXX.json"

    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console()
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)

    request = youtube.playlistItems().insert(
        part="snippet",
        body={
          "snippet": {
            "playlistId": "playlist-xy", #an actual playlistid
            "position": 0,
            "resourceId": {
              "kind": "youtube#video",
              "videoId": "videoid-xy" #an actual videoid
            }
          }
        }
    )
    response = request.execute()

    print(f"\n{response}")

if __name__ == "__main__":
    main()

Solution

  • Use the Batch Processing option provided by the API.

    Instead of creating individual requests, you create a batch and then add all the requests to it and then execute. Assuming you store all your video ids in a list videoIds:

    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)
    batch = youtube.new_batch_http_request()
    for videoId in videoIds:
        batch.add(youtube.playlistItems().insert(
            part="snippet",
            body={
              "snippet": {
                "playlistId": "playlist-xy", #an actual playlistid
                "position": 0,
                "resourceId": {
                  "kind": "youtube#video",
                  "videoId": videoId
                }
              }
            }
          )
        )
    responses = batch.execute()
    

    You can also set up a callback function which gets called for the response to each batch item. Info on that is provided on the page linked above.