728x90
우선 유튜브 API 키 발급은 아래 링크를 참고하자!
https://brunch.co.kr/@mystoryg/156
YouTube Data API 키 발급받기
YouTube Data API 키 발급받기 YouTube API를 사용하기 위해서는 키가 필요한데 발급받는 과정은 다음과 같다. 1) https://console.developers.google.com/apis 접속 후 좌측 라이브러리 선택 2) YouTube Data API v3 선택
brunch.co.kr
728x90
이후에
유튜브 업로드 하는 소스를 디버깅 하는데
API KEY 만 있으면 되는게 아니였다..!
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 401 when requesting https://youtube.googleapis.com/upload/youtube/v3/videos?part=****** 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'}]">
이 에러는 YouTube API를 호출할 때 API 키 대신 OAuth2 인증이 필요하다는 의미입니다. YouTube API의 일부 기능(특히 동영상 업로드)은 API 키만으로는 사용할 수 없으며, 사용자의 Google 계정 인증을 거치는 OAuth2 방식을 요구합니다.
문제의 원인
- googleapiclient 라이브러리를 사용할 때 동영상 업로드를 위한 videos().insert() 메서드는 API 키로만 인증이 불가능합니다.
- 동영상 업로드 같은 사용자 권한이 필요한 작업에서는 반드시 OAuth2 인증이 필요합니다.
해결 방법
1. OAuth2 인증 설정
YouTube API에서 동영상을 업로드하려면 OAuth 2.0 Client ID를 생성하고, 이를 통해 인증을 받아야 합니다. 아래는 필요한 단계입니다.
2. Google Cloud Console에서 OAuth 2.0 Client ID 생성
- Google Cloud Console에 접속:
- 프로젝트 선택:
- 동영상 업로드 API를 사용하려는 프로젝트를 선택합니다.
- OAuth 동의 화면 설정:
- 좌측 메뉴에서 API 및 서비스 > OAuth 동의 화면을 클릭.
- 외부(External)를 선택한 뒤, 앱 이름과 이메일 등의 필수 정보를 입력.
- 저장합니다.
- OAuth 2.0 클라이언트 ID 생성:
- API 및 서비스 > 사용자 인증 정보로 이동.
- 사용자 인증 정보 만들기 > OAuth 클라이언트 ID를 선택.
- 애플리케이션 유형으로 데스크톱 앱을 선택하고 생성.
- OAuth 2.0 클라이언트 ID 파일 다운로드:
- 생성된 클라이언트 ID를 선택하고, JSON 파일로 다운로드.
- 파일 이름을 client_secret.json으로 변경한 뒤, 스크립트 디렉토리에 저장합니다.
3. Python 코드 수정
YouTube API 클라이언트 인증을 위해 google-auth 라이브러리와 google-auth-oauthlib 라이브러리를 사용합니다.
import os
import json
import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors
SCOPES = ["https://www.googleapis.com/auth/youtube.upload"]
CLIENT_SECRET_FILE = "client_secret.json" # OAuth2 JSON 파일
def authenticate_youtube():
"""OAuth2 인증을 수행합니다."""
# 인증 흐름 시작
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
CLIENT_SECRET_FILE, SCOPES
)
credentials = flow.run_console() # 콘솔에서 사용자 인증 진행
return googleapiclient.discovery.build("youtube", "v3", credentials=credentials)
def upload_to_youtube(video_file, theme):
"""YouTube에 동영상을 업로드합니다."""
youtube = authenticate_youtube()
request_body = {
"snippet": {
"title": f"1시간 수면유도음악 - {theme['kor_name']} Sleep Music",
"description": f"Relaxing {theme['name']} sounds to help you sleep.",
"tags": ["sleep music", "relaxation", theme["name"]],
"categoryId": "10", # 음악 카테고리
},
"status": {
"privacyStatus": "public",
},
}
# 업로드할 비디오 파일을 MediaFileUpload로 감싸기
from googleapiclient.http import MediaFileUpload
media_file = MediaFileUpload(video_file, chunksize=-1, resumable=True)
# YouTube API 호출
request = youtube.videos().insert(
part="snippet,status",
body=request_body,
media_body=media_file
)
response = request.execute()
print(f"동영상 업로드 완료: {response['id']}")
# 테스트 실행
theme = {"kor_name": "테스트 테마", "name": "Rain Sounds"}
upload_to_youtube("sample_video.mp4", theme)
4. 코드 실행 과정
- 위 코드를 실행하면 Google 계정 로그인 URL이 출력됩니다.
- 해당 URL로 이동하여 Google 계정에 로그인하고, 동영상 업로드 권한을 승인합니다.
- 승인 후 콘솔에 표시된 인증 코드를 입력하면 인증이 완료됩니다.
- 이후 YouTube API 클라이언트를 통해 동영상 업로드가 가능합니다.
추가 참고
- OAuth 인증을 파일로 저장: 인증 정보를 매번 입력하는 대신, 인증 토큰을 저장해 다시 사용할 수 있습니다. 이를 위해 credentials.to_json()과 같은 방식을 사용해 인증 정보를 저장하고 불러올 수 있습니다.
- YouTube API 사용량 한도나 동영상 업로드 제한 정책을 확인하세요.
728x90
'개인프로젝트' 카테고리의 다른 글
[개인프로젝트] 유튜브 영상 업로드 - Pexels API 가이드 (2) | 2024.12.08 |
---|---|
[개인프로젝트 ] 유튜브 채널 영상 자동 업로드 : 환경셋팅 및 기본구성 (4) | 2024.12.07 |