この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。
はじめに
テントの中から失礼します、CX事業本部のてんとタカハシです!
以前、下記の記事で OAuth 2.0 の認証を通して YouTube Data API を叩く Python のコードを載っけました。
その際、YouTube Data API のドキュメントに記載してあるサンプルコードを参考したのですが、OAuth 2.0 の認証を通すために使用されているライブラリoauth2client
は大分前から非推奨になっているようです。
Note: oauth2client is now deprecated. No more features will be added to the libraries and the core team is turning down support. We recommend you use google-auth and oauthlib. For more details on the deprecation, see oauth2client deprecation.
GitHub - googleapis/oauth2client
大分前ってのはいつからかと言うと、どうも v4.1.0 のリリース時点で非推奨になったようなので、2017年5月11日からみたいです。ってことは3年半も前なのか。
GitHub - Release v4.1.0 and deprecate the library (#714)
ということで、この記事では代わりのgoogle-auth
を使用して OAuth 2.0 の認証を通すサンプルコードを載っけようと思います。
環境
$ sw_vers
ProductName: Mac OS X
ProductVersion: 10.14.6
BuildVersion: 18G103
$ python --version
Python 3.9.0
$ pip --version
pip 20.2.3 from /Users/<USER_NAME>/<PATH>/lib/python3.9/site-packages/pip (python 3.9)
準備
認証情報を作成する
下記の記事を参考にして、認証情報を含む JSON ファイルを作成してください。また、作成した認証情報のファイルはclient_secrets.json
にリネームして、これから実装するプログラムと同じディレクトリに格納してください。
必要なパッケージのインストール
下記のコマンドを実行します。
$ pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib
実装
こちらのサンプルコードを参考にして、YouTube Data API を叩く前に必要な認証を通します。コメントにも記載されていますが、初めて認証が通った際にtoken.pickle
というファイルが作成され、その中にアクセストークンやリフレッシュトークンが格納されます。
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
API_SERVICE_NAME = "youtube"
API_VERSION = "v3"
SCOPES = ["https://www.googleapis.com/auth/youtube"]
CLIENT_SECRETS_FILE = 'client_secrets.json'
def get_authenticated_service():
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# 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(
CLIENT_SECRETS_FILE, SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
return build(API_SERVICE_NAME, API_VERSION, credentials=creds)
if __name__ == "__main__":
youtube = get_authenticated_service()
# youtube.hoge() ... 動画を検索したり、アップロードしたり、再生リスト作ったり...
# サンプルコード: https://developers.google.com/youtube/v3/code_samples?hl=ja#python
Google APIs の OAuth 2.0 認証フロー周りについての詳細は下記をご参照ください。
Google Identity Platform - OAuth 2.0 Scopes for Google APIs
おわりに
YouTube Data API のドキュメントに記載されているサンプルコードは全然メンテされていないっぽいですね。他の方が書いた記事でもoauth2client
を使ったサンプルコードの紹介が多かったので、みんなドキュメントを参考にした結果なのかもしれません。この記事がどなたかのお役に立てば幸いです。
今回は以上になります。最後まで読んで頂きありがとうございました!