How to Automatically Upload Videos to YouTube Using Python

upload videos to youtube using python
upload videos to youtube using python

Estimated reading time: 6 minutes

Introduction

In today’s fast-paced digital world, automating repetitive tasks can save time and effort. For content creators and marketers, uploading videos to YouTube can be a tedious process if done manually. In this guide, we will walk you through the steps to automatically upload videos from a local folder to your YouTube channel using a Python script.

Prerequisites

Before you begin, ensure you have the following:

  1. Basic Knowledge of Python: Familiarity with Python programming is essential.
  2. Google Account: A Google account is necessary to access the YouTube Data API.
  3. Python Installed: Ensure you have Python 3.x installed on your computer.
  4. Access to the Command Line: You will need to run commands in the terminal or command prompt.

Step 1: Finding Your YouTube Playlist ID

If you want to add your uploaded videos into a YouTube playlist, then you need to find the ID for that playlist so we can automate it. Finding your YouTube playlist ID is a straightforward process. Here’s how to do it:

Method 1: From the YouTube Website

  1. Log into YouTube: Go to YouTube and log in to your account.
  2. Navigate to Your Playlists:
    • Click on your profile picture at the top right corner.
    • Select Your channel from the dropdown menu.
    • Click on the Playlists tab to view all your playlists.
  3. Select a Playlist: Click on the playlist for which you want to get the ID.
  4. Check the URL: Once the playlist page loads, look at the URL in your browser’s address bar. It should look something like this:
  5. Extract the Playlist ID: The playlist ID is the string of characters that follows list= in the URL. In this example, the playlist ID is:
  6. Copy the Playlist ID: Copy this ID, as you will need to replace the placeholder in your Python script with it.

Method 2: From the YouTube Studio

  1. Access YouTube Studio: Go to YouTube Studio and log in if prompted.
  2. Go to Playlists:
    • From the left sidebar, click on Playlists.
  3. Select a Playlist: Choose the playlist you want, and you’ll find the URL at the top of your browser with the same format as above.

Step 2: Setting Up the YouTube Data API

2.1 Create a Google Cloud Project

  1. Go to the Google Cloud Console.
  2. Click on the Select a project dropdown at the top.
  3. Click on New Project and enter a name for your project.
  4. Click Create.

2.2 Enable YouTube Data API v3

  1. In the Google Cloud Console, select your project.
  2. Navigate to the Library from the left sidebar.
  3. Search for YouTube Data API v3 and click on it.
  4. Click Enable to enable the API for your project.

2.3 Create OAuth 2.0 Credentials

  1. In the left sidebar, go to Credentials.
  2. Click on Create Credentials and select OAuth client ID.
  3. Configure the consent screen by providing the necessary information and save it.
  4. Select Desktop app as the application type and click Create.
  5. Click Download to save the client_secrets.json file to your computer.

Step 3: Install Required Libraries

Open your command line interface and run the following command to install the necessary libraries:

pip install google-auth google-auth-oauthlib google-api-python-client

Step 4: Prepare Your Video Files

  1. Create a folder named Uploads on your computer.
  2. Place all the .mp4 video files you want to upload into this folder.

Step 5: The Python Script

Copy and paste the following Python script into a file named main.py. Be sure to replace placeholders with your actual information where indicated.

import os
import json
import google.auth
import google.auth.transport.requests
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from datetime import datetime

# Scopes for managing YouTube uploads
SCOPES = ['https://www.googleapis.com/auth/youtube.upload']

# Authenticate and get credentials
def authenticate():
    creds = None
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(google.auth.transport.requests.Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file('client_secrets.json', SCOPES)
            creds = flow.run_local_server(port=0)

            with open('token.json', 'w') as token:
                token.write(creds.to_json())

    return creds

# Upload a video
def upload_video(video_file, title, description, tags, category_id="YOUR_CATEGORY_ID", privacy_status="public", playlist_id=None):
    credentials = authenticate()
    youtube = build('youtube', 'v3', credentials=credentials)

    # Get today's date in ISO 8601 format
    recording_date = datetime.utcnow().isoformat() + 'Z'

    request_body = {
        'snippet': {
            'title': title,
            'description': description,
            'tags': tags,
            'categoryId': category_id,
            'defaultLanguage': 'en-GB',  # Placeholder for language
            'recordingDetails': {
                'recordingDate': recording_date,
            }
        },
        'status': {
            'privacyStatus': privacy_status
        }
    }

    media = MediaFileUpload(video_file)

    response = youtube.videos().insert(
        part='snippet,status',
        body=request_body,
        media_body=media
    ).execute()

    video_id = response['id']
    print(f"Upload successful! Video ID: {video_id}")

    # If a playlist ID is provided, add the video to the playlist
    if playlist_id:
        youtube.playlistItems().insert(
            part='snippet',
            body={
                'snippet': {
                    'playlistId': playlist_id,
                    'resourceId': {
                        'kind': 'youtube#video',
                        'videoId': video_id
                    }
                }
            }
        ).execute()
        print(f"Video added to playlist: {playlist_id}")

# Example Usage
if __name__ == '__main__':
    video_directory = 'Uploads'  # Path to your "Uploads" folder
    video_files = [f for f in os.listdir(video_directory) if f.endswith('.mp4')]

    # Custom tags
    tags = ['YOUR_TAGS_HERE']  # Replace with your tags
    category_id = 'YOUR_CATEGORY_ID'  # Replace with your category ID
    playlist_id = 'YOUR_PLAYLIST_ID'  # Replace with your actual playlist ID

    for video_file in video_files:
        full_path = os.path.join(video_directory, video_file)
        title = os.path.splitext(video_file)[0]
        description = title  # Set description as the same as the title

        upload_video(full_path, title, description, tags, category_id, playlist_id)

Important Placeholders

  • YOUR_CATEGORY_ID: Replace this with your YouTube category ID. You can find a list of category IDs in the YouTube API documentation.
  • YOUR_PLAYLIST_ID: Replace this with the ID of the playlist where you want to add your videos.
  • YOUR_TAGS_HERE: Replace this with a comma-separated list of tags you want to associate with your videos.

Conclusion

Now you have a fully functional Python script that automatically uploads videos to your YouTube channel! You can customize the script further based on your needs.

Happy uploading!

Share this content:

Click to rate this post!
[Total: 0 Average: 0]
Avatar for Andrew Armstrong

About Andrew Armstrong

Founder of TechyGeeksHome and Head Editor for over 15 years! IT expert in multiple areas for over 26 years. Sharing experience and knowledge whenever possible! Making IT Happen.

View all posts by Andrew Armstrong

Leave a Reply

Your email address will not be published. Required fields are marked *