Python Youtube API v3 Uploading Video with API Key

Is it possible to upload videos to Youtube with python through the Youtube v3 API and an API Key?

from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload

API_KEY = 'API key'
file ='./path/to/file.mp4'

def upload_file():
    youtube = build('youtube', 'v3', developerKey=API_KEY)
    media_body=MediaFileUpload(file, chunksize=-1, resumable=True)
    body=dict(
        snippet=dict(
            title="test_title",
            description="something random description",
            tags=["soccer", "sports", "funny"],
            categoryId="22"
        ),
        status=dict(
            privacyStatus="private"
        )
    )

    youtube.videos().insert(
        part=",".join(body.keys()),
        body=body,
        media_body=media_body,
    ).execute()

upload_file()

With the provided code I receive the following error message:

<HttpError 401 when requesting None returned "API keys are not supported by this API. Expected OAuth2 access token or other authentication credentials that assert a principal. See https://cloud.google.com/docs/authentication". Details: "[{'message': 'Login Required.', 'domain': 'global', 'reason': 'required', 'location': 'Authorization', 'locationType': 'header'}]">

It should be a server side script, so without any user interaction for login for etc.

To upload videos to YouTube using the YouTube Data API v3, you cannot use just an API key. Instead, you need to use OAuth 2.0 for authentication. This requires obtaining an access token that grants permission to perform actions on behalf of the user.

Here’s how you can implement video uploads to YouTube with OAuth 2.0 in Python:

Steps to Set Up OAuth 2.0

  1. Create a Google Cloud Project:
  • Go to the Google Cloud Console.
  • Create a new project.
  • Enable the YouTube Data API v3 for your project.
  1. Create OAuth 2.0 Credentials:
  • Navigate to APIs & Services > Credentials.
  • Click on Create credentials and select OAuth client ID.
  • Configure the consent screen as required.
  • Choose Desktop app as the application type and create your credentials.
  • Download the credentials.json file.
  1. Install Required Libraries: Install the necessary libraries if you haven’t already:
pip install --upgrade google-api-python-client google-auth google-auth-oauthlib google-auth-httplib2

Sample Code for Video Upload

Here’s an example code snippet to upload a video to YouTube using OAuth 2.0:

import os
import google.auth
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload

# Scopes required for uploading videos
SCOPES = ['https://www.googleapis.com/auth/youtube.upload']

# Path to your credentials.json file
CREDENTIALS_FILE = 'path/to/credentials.json'
TOKEN_FILE = 'token.json'

def get_authenticated_service():
    creds = None
    # Load the token from the file if it exists
    if os.path.exists(TOKEN_FILE):
        creds = google.auth.load_credentials_from_file(TOKEN_FILE)
    # If there are no valid credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(CREDENTIALS_FILE, SCOPES)
            creds = flow.run_local_server(port=0)

        # Save the credentials for the next run
        with open(TOKEN_FILE, 'w') as token:
            token.write(creds.to_json())
    
    return build('youtube', 'v3', credentials=creds)

def upload_video(file_path):
    youtube = get_authenticated_service()
    media_body = MediaFileUpload(file_path, chunksize=-1, resumable=True)
    
    body = {
        'snippet': {
            'title': 'Test Title',
            'description': 'Something random description',
            'tags': ['soccer', 'sports', 'funny'],
            'categoryId': '22'
        },
        'status': {
            'privacyStatus': 'private'  # or 'public' or 'unlisted'
        }
    }

    request = youtube.videos().insert(
        part=','.join(body.keys()),
        body=body,
        media_body=media_body
    )
    
    response = request.execute()
    print(f"Video uploaded: {response['id']}")

if __name__ == '__main__':
    upload_video('./path/to/file.mp4')

Important Notes

  1. User Interaction:
  • The first time you run this script, it will open a browser window for you to log in and grant permissions.
  • The generated token.json will allow subsequent runs to upload without additional login.
  1. Service Account:
  • If you need to run this script in a server environment without user interaction, consider using a service account. However, service accounts cannot upload videos to YouTube directly since they need a YouTube channel associated with them. You’ll still need to use OAuth2 for user accounts.
  1. Privacy Status:
  • You can set privacyStatus to "private", "public", or "unlisted" based on your needs.

This should help you upload videos to YouTube programmatically using Python! Let me know if you have any further questions.