Search code examples
pythonyoutube-apiyoutube-data-apigcloud

Request had insufficient authentication scopes


Trying to update A yt video from being private to public

and im getting the following error :

googleapiclient.errors.HttpError: <HttpError 403 when requesting https://youtube.googleapis.com/youtube/v3/videos?part=id%2Csnippet%2Cstatus&alt=json returned "Request had insufficient authentication scopes.". Details: "[{'message': 'Insufficient Permission', 'domain': 'global', 'reason': 'insufficientPermissions'}]">

Only when trying the update method - The insert method works fine when uploading a video...

Here is how i authincate with Youtube-data-api:

import datetime
import pickle
import os
from google_auth_oauthlib.flow import Flow, InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload, MediaIoBaseDownload
from google.auth.transport.requests import Request


def Create_Service(client_secret_file, api_name, api_version, *scopes, force_pickle_file=""):
    print(client_secret_file, api_name, api_version, scopes, sep='-')
    print("CREDSSS : " + client_secret_file + "   " + str(scopes))
    CLIENT_SECRET_FILE = client_secret_file
    API_SERVICE_NAME = api_name
    API_VERSION = api_version
    SCOPES = [scope for scope in scopes[0]]
    print("[google_authentication] [Create_Service] Scopes : " + str(SCOPES))

    cred = None

    pickle_file = f'token_{API_SERVICE_NAME}_{API_VERSION}.pickle'
    # print(pickle_file)
    
    if force_pickle_file:
        pickle_file = force_pickle_file

    if os.path.exists(pickle_file):
        with open(pickle_file, 'rb') as token:
            cred = pickle.load(token)

    if not cred or not cred.valid:
        if cred and cred.expired and cred.refresh_token:
            cred.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES)
            cred = flow.run_local_server()

        with open(pickle_file, 'wb') as token:
            pickle.dump(cred, token)

    try:
        service = build(API_SERVICE_NAME, API_VERSION, credentials=cred)
        print('[google_authentication] [Create_Service] service created successfully - ' + str(API_SERVICE_NAME))
        return service
    except Exception as e:
        print('[google_authentication] [Create_Service] Unable to connect.')
        print("[google_authentication] [Create_Service] ERROR : " + str(e))
        return None

def convert_to_RFC_datetime(year=1900, month=1, day=1, hour=0, minute=0):
    dt = datetime.datetime(year, month, day, hour, minute, 0).isoformat() + 'Z'
    return dt

YT_handler.py:


update_public_request_body = {
    "id": "",
    'status': {
        'privacyStatus': 'public'
    }
}

###

API_NAME = 'youtube'
API_VERSION = 'v3'
SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']



def set_vid_public(CLIENT_SECRET_FILE: str, video_id: str, pickle_file: str = "") -> dict:

    print("[yt_handler] [set_vid_public] Authenicatin with Google account...")

    # Creating an authorization pickle..
    service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES, force_pickle_file=pickle_file)

    request_body = update_public_request_body
    request_body["id"] = video_id # Setting the desiered video id in request body

    print("[yt_handler] [set_vid_public] Started updating video status...")

    response_upload = service.videos().insert(
        part='id,snippet,status',
        body=request_body,
    ).execute()

    print("[yt_handler] [set_vid_public] SUCCESS - Video status set to Public!")

    return response_upload

And here is my Main:

import os
import sys
import __main__

# Adding libs to path
libs = os.getcwd() + "/libs"
sys.path.insert(1, str(libs))


import yt_handler

ggl_auth_secret_file = os.getcwd()+'/secrets/yt_client_secert.json'
ggl_auth_pickle_file = os.getcwd()+'/secrets/token_youtube_v3.pickle'

yt_handler.set_vid_public(ggl_auth_secret_file, "Bi6Mf2Xxnbk", pickle_file = ggl_auth_pickle_file)

What am i doing wrong here??

I was expecting the api to fail on some other than an authentication error

and to update the video status


Solution

  • You have probably already authorized this script once and then changed the scope.

    the issue is the the user tokens are stored in pickle_file with the original scope you requested.

    delete that file you script should request authorization of the user again this time with the required scope