Uwaga: interfejs YouTube Content ID API jest przeznaczony dla dostawców treści w YouTube i nie jest dostępny dla wszystkich deweloperów ani użytkowników YouTube. Jeśli nie widzisz interfejsu YouTube Content ID API na liście usług wymienionych w Konsoli interfejsów API Google, odwiedź Centrum pomocy YouTube, aby dowiedzieć się więcej o programie partnerskim YouTube.
Ten samouczek krok po kroku pokazuje, jak utworzyć skrypt, który łączy się z usługą ContentOwnersService
i pobiera informacje o danym właścicielu treści. Pełny przykładowy kod znajdziesz na końcu samouczka. Chociaż kod jest napisany w Pythonie, dostępne są również biblioteki klienta dla innych popularnych języków programowania.
Wymagania
- Python 2.5 lub nowszy
- google-api-python-client
Tworzenie skryptu do wysyłania żądań do interfejsu API
Poniżej opisujemy, jak utworzyć skrypt wysyłający żądanie do interfejsu YouTube Content ID API.
Krok 1. Utwórz podstawowy skrypt
Poniższy skrypt akceptuje te parametry wiersza poleceń i ustawia wartości w globalnej zmiennej FLAGS
:
- Parametr
content_owner_id
jest wymagany i wskazuje właściciela treści w systemie CMS, o którym chcesz pobrać informacje. - Parametr
logging_level
określa poziom szczegółowości rejestrowania skryptu. - Parametr
help
powoduje, że skrypt generuje listę parametrów, które rozumie.
#!/usr/bin/python2.6 # -*- coding: utf-8 -*- import gflags import logging import sys import os from datetime import * # Define flags. The gflags module makes it easy to define command-line params # for an application. Run this program with the '--help' argument to see all # of the flags that it understands. FLAGS = gflags.FLAGS gflags.DEFINE_string('content_owner_id', None, ('Required flag. ' 'Identifies the content owner whose details are printed out.')) gflags.MarkFlagAsRequired('content_owner_id') gflags.DEFINE_enum('logging_level', 'ERROR', ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], 'Set the level of logging detail.') def main(argv): # Let the gflags module process the command-line arguments try: argv = FLAGS(argv) except gflags.FlagsError, e: print '%s\nUsage: %s ARGS\n%s' % (e, argv[0], FLAGS) sys.exit(1) # Set the logging according to the command-line flag logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level)) if __name__ == '__main__': main(sys.argv)
Krok 2. Włącz uwierzytelnianie i autoryzację użytkowników
W tym kroku umieścimy w skrypcie autoryzację OAuth 2.0. Dzięki temu użytkownik, który uruchamia skrypt, może autoryzować skrypt do wykonywania żądań interfejsu API przypisanych do konta użytkownika.
Krok 2a. Utwórz plik client_secrets.json
Interfejs YouTube Content ID API do przeprowadzenia uwierzytelniania wymaga pliku client_secrets.json
zawierającego informacje z Konsoli API. Musisz też zarejestrować swoją aplikację. Bardziej szczegółowe informacje o tym, jak działa uwierzytelnianie, znajdziesz w przewodniku po uwierzytelniania.
{ "web": { "client_id": "INSERT CLIENT ID HERE", "client_secret": "INSERT CLIENT SECRET HERE", "redirect_uris": [], "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token" } }
Krok 2b. Dodaj do skryptu kod uwierzytelniający
Aby włączyć uwierzytelnianie i autoryzację użytkownika, musisz dodać te instrukcje import
:
from oauth2client.file import Storage from oauth2client.client import flow_from_clientsecrets from oauth2client.tools import run
Następnie utworzymy obiekt FLOW
z użyciem tajnych kluczy klienta skonfigurowanych w kroku 2a. Jeśli użytkownik autoryzuje naszą aplikację do przesyłania żądań interfejsu API w imieniu użytkownika, uzyskane dane uwierzytelniające są przechowywane 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://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, storage)
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 autoryzacji.
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 wchodzić w interakcję 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 żądanie usługi. 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=FLAGS.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'])
Wypełnij zgłoszenie
Ta sekcja zawiera pełną aplikację z informacjami o licencji i dodatkowymi komentarzami w skrypcie. Program można prowadzić na 2 sposoby:
-
Polecenie to uruchamia okno przeglądarki, w którym możesz w razie potrzeby uwierzytelnić się i autoryzować aplikację do przesyłania żądań do interfejsu API. Jeśli autoryzujesz aplikację, dane uwierzytelniające są automatycznie przesyłane z powrotem do skryptu.
python yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID.
Uwaga: wartość
CONTENT_OWNER_ID
dla swojego konta znajdziesz na stronie Ustawienia konta na koncie CMS. Ta wartość jest podana jakoPartner Code
w sekcji informacji o koncie na tej stronie. -
Polecenie to generuje adres URL, który można otworzyć w przeglądarce, i prosi o podanie kodu autoryzacji. Gdy otworzysz taki adres URL, możesz autoryzować aplikację do przesyłania żądań do interfejsu API w Twoim imieniu. Po uzyskaniu autoryzacji na stronie pojawi się kod autoryzacji, który musisz wpisać w oknie, które wyświetli się w oknie procedury autoryzacji.
python yt_partner_api.py --content_owner_id=CONTENT_OWNER_ID --noauth_local_webserver.
Uwaga: moduł
oauth2client
rozpoznaje parametrnoauth_local_webserver
, mimo że nie jest on wymieniony w skrypcie.
client_secrets.json
{ "web": { "client_id": "INSERT CLIENT ID HERE", "client_secret": "INSERT CLIENT SECRET HERE", "redirect_uris": [], "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token" } }
yt_partner_api.py
#!/usr/bin/python2.6 # -*- coding: utf-8 -*- # # 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 Content ID API. Command-line application that retrieves the information about given content owner. Usage: $ python yt_partner_api.py --content_owner_id=[contentOwnerId] $ python 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: $ python yt_partner_api.py --help To get detailed log output run: $ python yt_partner_api.py --logging_level=DEBUG \ --content_owner_id=[contentOwnerId] """ import gflags import httplib2 import logging import sys import os from datetime import * from apiclient.discovery import build from oauth2client.file import Storage from oauth2client.client import flow_from_clientsecrets from oauth2client.tools import run # Define flags. The gflags module makes it easy to define command-line options # for an application. Run this program with the '--help' argument to see all # of the flags that it understands. FLAGS = gflags.FLAGS gflags.DEFINE_string('content_owner_id', None, ('Required flag. ' 'Identifies the content owner id whose details are printed out.')) gflags.MarkFlagAsRequired('content_owner_id') gflags.DEFINE_enum('logging_level', 'ERROR', ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], 'Set the level of logging detail.') def main(argv): # Let the gflags module process the command-line arguments try: argv = FLAGS(argv) except gflags.FlagsError, e: print '%s\nUsage: %s ARGS\n%s' % (e, argv[0], FLAGS) sys.exit(1) # Set the logging according to the command-line flag logging.getLogger().setLevel(getattr(logging, FLAGS.logging_level)) # Set up a Flow object to be used if we need to authenticate. FLOW = flow_from_clientsecrets('client_secrets.json', scope='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, storage) http = httplib2.Http() http = credentials.authorize(http) service = build("youtubePartner", "v1", http=http) contentOwnersService = service.contentOwners() # Create and execute get request. request = contentOwnersService.get(contentOwnerId=FLAGS.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(sys.argv)