I have a relatively simple script to authenticate my google account with the youtube data API so that I may manage my channel from the commandline for purposes such as scheduling streams and modifying their title. I have tried using different google accounts for creating and setting up the youtube data api and credentials in the google cloud console, as well as authenticating with different accounts. I cannot get this auth script to work. It launches my web browser, and no matter what google account I select to login with, it fails by saying either something went wrong please try again or it brings me to an error 400 screen that says “the server cannot process the request because it is malformed. It should not be retried. That’s all we know”.
I have also tried playing with the flow.run_local_server() port. I have tried not passing a port, and i have tried ports 0 and 8080. the redirect URI in my client_secrets.json is simply localhost with no ports. How can I debug? Why might this not be working?
import os
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
SCOPES = ['https://www.googleapis.com/auth/youtube.readonly']
CLIENT_SECRETS_FILE = 'client_secrets.json'
def authenticate_youtube():
creds = None
# Check if the token exists
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# Refresh or initiate authentication
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(CLIENT_SECRETS_FILE, SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for future use
with open('token.json', 'w') as token:
token.write(creds.to_json())
# Build YouTube service
youtube = build('youtube', 'v3', credentials=creds)
return youtube