Upload videos to YouTube Brand Account via API

2021-03-21

Background

A Brand Account in YouTube means an additional channel attached to a Google account. It enables YouTubers to use a new channel name rather than showing their Google profile name. Refer to YouTube Help if you’re interested in YouTube Brand Account.

The common way to upload a video is visiting the YouTube Studio website, but in several cases people have to use API to do the job. For example, in a headless remote machine, you have 100 video files to upload, and they are so large that you can’t afford the data expense if you download & upload with your local computer.

Although there are abundant resources about uploading YouTube videos by API/CLI (example 1 , example 2 ), most of them doesn’t work with a brand account (another report ). That’s because they call APIs through SDKs. And the SDKs, such as googleapiclient.http.MediaFileUpload in Python, use a client-secret file for authentication, which did not give you an option to choose a brand account.

As much as I investigated, it’s not difficult to upload a video to YouTube Brand Channel through API, but the online community lack a complete guide for this operation.

Requirement

  • A YouTube/Google Brand account
  • Document reading skills
  • A little knowledge of Python code
  • A little knowledge of network programming

The Approach

It’s a 4-step solution: setup, authentication, meta-data preparation, and uploading.

1. Setup

Follow the steps described here , while the JSON file is not needed. Instead, keep the pair of Client ID and Client secret for later use.

It’s also required to enable the YouTube Data API on Google Could Console .

2. Authentication

Follow the steps for brand account authentication to get the refresh token. A refresh token can work for a few days before expiration. When it’s expired, just get a new one.

The refresh token is required to get the access token. Below is a Python example to get access token by sending the refresh token, Client ID, and Client secret acquired previously.

import requests
payload = {
    "client_id": "Lorem ipsum",
    "client_secret":"Lorem ipsum",
    "refresh_token":"Lorem ipsum",
    "grant_type":"refresh_token"
}
r = requests.post("https://oauth2.googleapis.com/token", data=payload)
access_token = r.json()['access_token']

Alternatively, the same operation can be done on Postwoman . If everything goes well, you will be authenticated with the string access_token.

Access token is the major token to verify your identity in later steps, which have a shorter life (3600s) than refresh token. Please keep the token for later use.

3. Video meta-data preparation

In the YouTube developer document, there are 3 pages about uploading videos: Upload a Video , Videos: insert , and Resumable Uploads . The first two didn’t mention any token to use, while the 3rd page involves a AUTH_TOKEN.

In result, Send Resumable Uploads is chosen to follow so that we can utilize the access token we got before. To understand what you are going to do, it’s recommend to read through Step 1 - Start a resumable session and Step 2 - Save the resumable session URI describe how to prepare meta-data for videos.

Following is a Python example of step 1 & 2 on Resumable Uploads .

import json
import requests
from pathlib import Path

file_to_upload =  "/your_path/Lorem ipsum.mp4"
payload = {
  "snippet": {
    "title": "Lorem ipsum",
    "description": 'example\nLorem ipsum',
    "tags": ["example", "Lorem", "ipsum"],
    "categoryId": 22 # https://gist.github.com/dgp/1b24bf2961521bd75d6c
  },
  "status": {
    "privacyStatus": "public",
    "embeddable": True,
    "license": "youtube"
  }
}
payload = json.dumps(payload)
headers = {
    "authorization": "Bearer "+access_token, # Got before
    # "content-length": str(len(payload)), # not a necessary field
    "content-type": "application/json; charset=utf-8",
    "x-upload-content-length": str(Path(file_to_upload).stat().st_size),
    "X-Upload-Content-Type": "application/octet-stream"
}
r = requests.post("https://www.googleapis.com/upload/youtube/v3/videos?uploadType=resumable&part=snippet,status,contentDetails", data=payload, headers=headers)
upload_url = r.headers["Location"]

If any error show up when getting r.headers["Location"], please check by r.json(). The most common reason is the access_token expiration. If that happend, just get a new one according to previous instrctions.

4. Uploading

If the video file to upload is small in file size, or if you can afford a big RAM, go on Step 3 - Upload the video file . Otherwise, Upload a file in chunks .

After reading the description of API as this page provided, here we can find a piece of code similar to what we need, and then modify it into the piece shown below.

from pathlib import Path
def read_in_chunks(file_object, chunk_size=32*1024*1024): # or your favorite chunk size
    while True:
        data = file_object.read(chunk_size)
        if not data:
            break
        yield data

f = open(file_to_upload, mode='rb')
firstByte, lastByte, totalByte = 0, 0, str(Path(file_to_upload).stat().st_size)
print(upload_url)

for chunk in read_in_chunks(f):
    lastB = firstB + len(chunk) - 1
    up_file_headers = {
        "authorization": "Bearer "+access_token,
        "Content-Length": str(len(chunk)),
        "Content-Range": f"bytes {firstByte}-{lastByte}/{totalByte}",
        "Content-Type": "application/octet-stream"
    }
    try:
        r = requests.put(upload_url, data=chunk, headers=up_file_headers)
        print(f"r: {r}, Content-Range: {up_file_headers['Content-Range']}")
        firstByte = lastByte + 1
    except Exception as e:
        # your custom error handling
        raise e

Normally within the loop, the calls return 308, except the last call returning 200.

Finally, enjoy your new YouTube video!

Conclusion

Uploading YouTube videos via API is a longer journey than uploading on its web UI (aka YouTube Studio). However, life wasn’t so hard in the good old days . When YouTube’s traditional uploading interface was available, videos can be imported from Google Drive directly or through Google Photos.

We can see an obvious trend that Google is gradually revoking their promised services. Be careful with Google.

Homeworks

Please try to answer following questions.

  1. Is there any limitation to uploading by APi?
  2. If so, what to do if you want to upload more than limitation?
  3. Assume your uploading progress was interrupted by some network issue or I/O error. How to deal with it?

Feel free to leave your answers or ideas in the comments section below.

Example answers to previous homeworks

  1. omitted.
  2. GitHub services can be down .
  3. Depending on the shape and size of data, as well as how people use the data.
OperationGuidegoogleapiyoutubevideo



Support Me

您可以 打赏 支持本文作者

Compress videos using Azure

Non-interactive rclone configuration for SharePoint with custom API