YouTube API: Upload Videos With Python

by Admin 39 views
YouTube API: Upload Videos with Python

Hey guys! Want to automate your YouTube uploads using Python? You've come to the right place! In this guide, we'll walk through the process of using the YouTube Data API to upload videos programmatically. This can be super useful for automating content delivery, creating scheduled uploads, or integrating video uploads into your existing applications. Let's dive in!

Prerequisites

Before we get started, make sure you have a few things in place:

  • Google Cloud Project: You'll need a Google Cloud Project with the YouTube Data API enabled.
  • Python Environment: Ensure you have Python installed on your system. Python 3.6+ is recommended.
  • Google API Client Library: Install the google-api-python-client library. You can do this using pip: pip install google-api-python-client google-auth-httplib2 google-auth-oauthlib
  • Credentials: You'll need API credentials to authorize your application to upload videos. We'll cover this in detail below.

Setting Up Your Google Cloud Project

First, head over to the Google Cloud Console and either select an existing project or create a new one. Once you have a project, you need to enable the YouTube Data API v3. Here’s how:

  1. Navigate to the API Library. You can find this by using the search bar at the top and typing “API Library.”
  2. Search for “YouTube Data API v3” and select it.
  3. Click Enable. This will activate the API for your project.

Next, you need to create credentials. For a simple desktop application, an OAuth 2.0 Client ID is generally the easiest to use. Here’s how to create one:

  1. Go to the Credentials page (you can search for “Credentials” in the console).
  2. Click Create Credentials and select OAuth client ID.
  3. You may be prompted to configure the consent screen. If so, click Configure consent screen. Choose the External user type unless you are part of a Google Workspace organization. Fill out the required information (app name, support email, etc.) and click Save and Continue. You can add scopes later, so just click Save and Continue through the Scopes section. Add any test users if necessary, then click Save and Continue and finally, Back to Dashboard.
  4. Back on the Create Credentials page, select OAuth client ID again.
  5. Choose Desktop app as the application type and give it a name.
  6. Click Create. You’ll get a popup with your Client ID and Client Secret. Download these as you'll need them soon. Keep them safe, especially the client secret!

Installing the Google API Client Library

Make sure you have the Google API Client Library for Python installed. If you haven't already, use pip:

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

This command installs the necessary libraries for interacting with the YouTube API.

Writing the Python Script

Now for the fun part – writing the Python script to upload your video! Here’s a basic example to get you started. We'll break down each section.

import googleapiclient.discovery
import googleapiclient.errors
from google_auth_oauthlib.flow import InstalledAppFlow
import google.auth.transport.requests
import os

# Define the scopes.  These are the permissions we're asking for.
SCOPES = ['https://www.googleapis.com/auth/youtube.upload']
CLIENT_SECRETS_FILE = 'path/to/your/client_secret.json' # Replace with the actual path

API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'

def get_authenticated_service():
    flow = InstalledAppFlow.from_client_secrets_file(
        CLIENT_SECRETS_FILE,
        SCOPES
    )
    creds = flow.run_local_server(port=0)
    return googleapiclient.discovery.build(
        API_SERVICE_NAME,
        API_VERSION,
        credentials=creds
    )

def upload_video(youtube, file, title, description, category_id, keywords):
    body = {
        'snippet': {
            'title': title,
            'description': description,
            'tags': keywords,
            'categoryId': category_id
        },
        'status': {
            'privacyStatus': 'private' # or 'public' or 'unlisted'
        }
    }

    # Call the API's videos.insert method to create and upload the video.
    try:
        request = youtube.videos().insert(
            part=','.join(body.keys()),
            body=body,
            media_body=file
        )
        response = request.execute()

        print(f"Video '{title}' was successfully uploaded.")
        print(f"Video ID: {response['id']}")

    except googleapiclient.errors.HttpError as e:
        print(f"An HTTP error {e.resp.status} occurred:\n{e.content}")

def main():
    # Authenticate and construct service.
    youtube = get_authenticated_service()

    # Provide video details
    video_file_path = 'path/to/your/video.mp4'  # Replace with your video file
    title = 'My Awesome Video'
    description = 'This is a description of my awesome video.'
    category_id = '22'  # Entertainment category
    keywords = ['python', 'youtube', 'api', 'upload']

    # Create a MediaFileUpload instance.
    media = googleapiclient.http.MediaFileUpload(
        video_file_path,
        mimetype='video/mp4',
        resumable=True
    )

    # Upload the video.
    upload_video(youtube, media, title, description, category_id, keywords)

if __name__ == '__main__':
    main()

Breaking Down the Code

Let's break down the script piece by piece so you understand what’s going on. This ensures you can adapt it to your specific needs.

Importing Libraries

import googleapiclient.discovery
import googleapiclient.errors
from google_auth_oauthlib.flow import InstalledAppFlow
import google.auth.transport.requests
import os

These lines import the necessary libraries for interacting with the YouTube API, handling authentication, and dealing with potential errors.

Defining Scopes and Credentials

SCOPES = ['https://www.googleapis.com/auth/youtube.upload']
CLIENT_SECRETS_FILE = 'path/to/your/client_secret.json'

API_SERVICE_NAME = 'youtube'
API_VERSION = 'v3'
  • SCOPES: This defines the permissions your application needs. Here, we're asking for permission to upload videos to YouTube.
  • CLIENT_SECRETS_FILE: This should be the path to the client_secret.json file you downloaded from the Google Cloud Console when you created your OAuth client ID. Make sure to replace the placeholder with the actual path to your file.
  • API_SERVICE_NAME and API_VERSION: These specify which API service and version you’re using (YouTube and v3, respectively).

Authenticating the Service

def get_authenticated_service():
    flow = InstalledAppFlow.from_client_secrets_file(
        CLIENT_SECRETS_FILE,
        SCOPES
    )
    creds = flow.run_local_server(port=0)
    return googleapiclient.discovery.build(
        API_SERVICE_NAME,
        API_VERSION,
        credentials=creds
    )

This function handles the authentication process. It uses the InstalledAppFlow to guide the user through the OAuth 2.0 flow. When you run the script, it will open a browser window asking you to authenticate and grant permission to your application. The run_local_server(port=0) part automatically selects an available port for the local server that handles the authentication redirect. After authentication, it builds the YouTube API service object with the obtained credentials.

Uploading the Video

def upload_video(youtube, file, title, description, category_id, keywords):
    body = {
        'snippet': {
            'title': title,
            'description': description,
            'tags': keywords,
            'categoryId': category_id
        },
        'status': {
            'privacyStatus': 'private' # or 'public' or 'unlisted'
        }
    }

    try:
        request = youtube.videos().insert(
            part=','.join(body.keys()),
            body=body,
            media_body=file
        )
        response = request.execute()

        print(f"Video '{title}' was successfully uploaded.")
        print(f"Video ID: {response['id']}")

    except googleapiclient.errors.HttpError as e:
        print(f"An HTTP error {e.resp.status} occurred:\n{e.content}")

This function takes the YouTube service object, the video file, and metadata as input. It constructs the body dictionary, which contains information about the video, such as the title, description, tags, category, and privacy status. The videos().insert method is then called to upload the video. The part parameter specifies which parts of the video resource you are setting (snippet and status in this case). The media_body parameter is set to the video file. Error handling is included to catch and print any HTTP errors that may occur during the upload process. You can set 'privacyStatus' to 'public', 'private', or 'unlisted' as per your requirement.

Main Function

def main():
    youtube = get_authenticated_service()

    video_file_path = 'path/to/your/video.mp4'
    title = 'My Awesome Video'
    description = 'This is a description of my awesome video.'
    category_id = '22'
    keywords = ['python', 'youtube', 'api', 'upload']

    media = googleapiclient.http.MediaFileUpload(
        video_file_path,
        mimetype='video/mp4',
        resumable=True
    )

    upload_video(youtube, media, title, description, category_id, keywords)

if __name__ == '__main__':
    main()

The main function orchestrates the entire process. It first authenticates the service using get_authenticated_service(). Then, it defines the video file path, title, description, category ID, and keywords. A MediaFileUpload instance is created to represent the video file. The mimetype is set to 'video/mp4', but you should adjust this if you’re uploading a different video format. The resumable=True parameter enables resumable uploads, which are helpful for large files. Finally, it calls the upload_video function to upload the video to YouTube. Don't forget to replace the placeholder values with your actual video file path and desired metadata!

Running the Script

  1. Save the script: Save the code to a file, such as upload_video.py.
  2. Replace placeholders: Update the CLIENT_SECRETS_FILE and video_file_path variables with the correct paths.
  3. Run the script: Open your terminal or command prompt, navigate to the directory where you saved the script, and run python upload_video.py.
  4. Authenticate: The script will open a browser window asking you to authenticate. Follow the prompts to grant permission to your application.
  5. Upload: Once authenticated, the script will upload the video to your YouTube channel.

Handling Different Video Categories

The category_id parameter in the upload_video function specifies the category of the video. YouTube uses numeric IDs to represent different categories. Here are a few common categories:

  • 2: Autos & Vehicles
  • 1: Film & Animation
  • 10: Music
  • 15: Pets & Animals
  • 17: Sports
  • 19: Travel & Events
  • 20: Gaming
  • 22: People & Blogs
  • 23: Comedy
  • 24: Entertainment
  • 25: News & Politics
  • 26: Howto & Style
  • 27: Education
  • 28: Science & Technology

You can find a more comprehensive list of categories and their corresponding IDs in the YouTube API documentation.

Making the Video Public

In the script, the privacyStatus is set to 'private'. If you want to make the video public, change it to 'public'.

'status': {
    'privacyStatus': 'public'
}

Alternatively, you can set it to 'unlisted' if you want the video to be accessible only to those who have the link.

Conclusion

And that's it! You've successfully uploaded a video to YouTube using the YouTube Data API and Python. This opens up a world of possibilities for automating your video uploads and integrating them into your applications. Experiment with different settings, explore the API documentation, and have fun automating your YouTube workflow! Happy coding!