Il YouTubeVideoUploadService
consente di caricare i video direttamente su YouTube tramite l'API Google Ads. Questi
video possono essere utilizzati per creare asset video in vari tipi di annunci, ad esempio
campagne Performance Max o
campagne Demand Gen.
Questo servizio semplifica il flusso di lavoro di creazione degli annunci video gestendo la procedura di caricamento di YouTube e assicurandosi che i video siano associati correttamente al tuo account.
Concetti fondamentali
Prima di iniziare, è importante capire come vengono gestiti i caricamenti di video e i diversi stati che possono assumere.
Proprietà del canale
Quando carichi un video, puoi specificare il canale YouTube di destinazione utilizzando
il campo channel_id nella risorsa YouTubeVideoUpload:
- Canale di proprietà dell'inserzionista (brand): fornisci il
channel_iddi un canale YouTube esistente di proprietà dell'inserzionista. Questa opzione è supportata solo con il flusso di autenticazione dell'utente; non può essere utilizzata con i service account. - Canale gestito da Google: se
channel_idviene omesso, il video viene caricato su un canale YouTube gestito da Google associato all'account Google Ads.
Stati di caricamento
Il ciclo di vita di un caricamento di video di YouTube viene monitorato dal campo state.
L'YouTubeVideoUploadState
enumerazione definisce i seguenti stati:
| Stato | Descrizione |
|---|---|
PENDING |
Il video è in fase di caricamento. |
UPLOADED |
Il video è stato caricato correttamente ed è in fase di elaborazione da parte di YouTube. |
PROCESSED |
Il video è stato elaborato correttamente ed è pronto per l'uso. |
FAILED |
Il caricamento o l'elaborazione non è riuscito e non può essere completato. |
REJECTED |
Il video è stato rifiutato per motivi di convalida o di norme. |
UNAVAILABLE |
Lo stato del video non è disponibile; potrebbe essere stato rimosso da YouTube. |
Impostazioni privacy
Il campo video_privacy controlla chi può vedere il video caricato. L'
YouTubeVideoPrivacy
enumerazione supporta:
PUBLIC: il video è disponibile per chiunque su YouTube. (Consentito solo per i canali del brand).UNLISTED: il video non è ricercabile, ma può essere visualizzato da chiunque abbia il link. Questa è l'opzione predefinita e l'unica per i canali gestiti da Google.
Carica un video
Per caricare un video, devi utilizzare una richiesta in più parti al metodo CreateYouTubeVideoUpload. La richiesta contiene sia i metadati per il caricamento sia il file video stesso.
1. Avvia il caricamento
Crea un oggetto CreateYouTubeVideoUploadRequest
specificando:
customer_id: il tuo ID cliente Google Ads.you_tube_video_upload: un oggettoYouTubeVideoUploadconvideo_title,video_descriptione, facoltativamente,channel_idevideo_privacy.
Se utilizzi una libreria client, chiama il
CreateYouTubeVideoUpload
metodo, passando il file video, e il caricamento del video verrà gestito
internamente.
Java
This example is not yet available in Java; you can take a look at the other languages.
C#
This example is not yet available in C#; you can take a look at the other languages.
PHP
This example is not yet available in PHP; you can take a look at the other languages.
Python
yt_service: YouTubeVideoUploadServiceClient = client.get_service( "YouTubeVideoUploadService" ) create_upload_request: CreateYouTubeVideoUploadRequest = ( youtube_video_upload_service.CreateYouTubeVideoUploadRequest() ) create_upload_request.customer_id = customer_id create_upload_request.you_tube_video_upload.video_title = "Test Video" create_upload_request.you_tube_video_upload.video_description = ( "Test Video Description" ) create_upload_request.you_tube_video_upload.video_privacy = ( client.enums.YouTubeVideoPrivacyEnum.UNLISTED ) video_upload_resource_name: str with open(video_file_path, "rb") as stream: response: CreateYouTubeVideoUploadResponse = ( yt_service.create_you_tube_video_upload( stream=stream, request=create_upload_request, retry=None, ) ) video_upload_resource_name = response.resource_name print(f"Created YouTube video upload: {video_upload_resource_name}")
Ruby
This example is not yet available in Ruby; you can take a look at the other languages.
Perl
This example is not yet available in Perl; you can take a look at the other languages.
curl
# # Use the --i curl parameter to capture response headers in the $RESPONSE # variable. FILE_SIZE=$(wc -c < "${VIDEO_FILE_NAME}" | tr -d '\r') RESPONSE=$(curl -i -f -v -s --request POST \ "https://googleads.googleapis.com/resumable/upload/v${API_VERSION}/customers/${CUSTOMER_ID}/youTubeVideoUploads:create" \ --header "Content-Type: application/json" \ --header "developer-token: ${DEVELOPER_TOKEN}" \ --header "login-customer-id: ${MANAGER_CUSTOMER_ID}" \ --header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \ --header "X-Goog-Upload-Protocol: resumable" \ --header "X-Goog-Upload-Command: start" \ --header "X-Goog-Upload-Header-Content-Length: ${FILE_SIZE}" \ --data @- <<EOF { "customer_id": "${CUSTOMER_ID}", "you_tube_video_upload": { "video_title": "${VIDEO_TITLE}", "video_description": "${VIDEO_DESCRIPTION}", "video_privacy": "UNLISTED" } } EOF ) # Extract the value of the "x-goog-upload-url" header from the HTTP response. UPLOAD_URL=$(echo "${RESPONSE}" \ | grep -i '^x-goog-upload-url' \ | awk '{print $2}' \ | tr -d '\r') CHUNK_SIZE=$(echo "${RESPONSE}" \ | grep -i '^x-goog-upload-chunk-granularity' \ | awk '{print $2}' \ | tr -d '\r')
Se utilizzi REST, la sezione seguente descrive come gestire il caricamento del video.
2. Carica il video
Quando invii una richiesta REST al
CreateYouTubeVideoUpload
metodo, la risposta contiene l'URL da utilizzare per caricare i byte del video
nell'intestazione della risposta HTTP x-goog-upload-url, insieme ad altri metadati come
la dimensione prevista di ogni blocco per i caricamenti a blocchi.
Puoi anche dichiarare inizialmente la dimensione del video che caricherai, quando avvii la procedura, con l'intestazione della richiesta HTTP x-goog-upload-header-content-length.
Per una descrizione completa delle intestazioni HTTP utilizzate nel protocollo di caricamento dei video, consulta il seguente esempio di codice:
# Take the first ${CHUNK_SIZE} bytes of the video file and upload them. head -c ${CHUNK_SIZE} ${VIDEO_FILE_NAME} | curl -i -v -X PUT "${UPLOAD_URL}" \ --header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \ --header "X-Goog-Upload-Offset: 0" \ --header "X-Goog-Upload-Command: upload" \ --header "Content-Length: ${CHUNK_SIZE}" \ --data-binary @- # Query the status of the upload. QUERY_RESPONSE=$(curl -i -s -X POST "${UPLOAD_URL}" \ --header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \ --header "X-Goog-Upload-Command: query") # Extract the value of the "x-goog-upload-size-received" header from the HTTP # response. UPLOADED_BYTES=$(echo "${QUERY_RESPONSE}" \ | grep -i '^x-goog-upload-size-received' \ | awk '{print $2}' \ | tr -d '\r') echo "Uploaded ${UPLOADED_BYTES} bytes." REMAINING_BYTES=$((FILE_SIZE - UPLOADED_BYTES)) echo "${REMAINING_BYTES} bytes remaining to upload." FINALIZE_RESPONSE=$(tail -c ${REMAINING_BYTES} ${VIDEO_FILE_NAME} | curl -v -X PUT "${UPLOAD_URL}" \ --header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \ --header "X-Goog-Upload-Offset: ${UPLOADED_BYTES}" \ --header "X-Goog-Upload-Command: upload, finalize" \ --data-binary @-) UPLOADED_VIDEO_RESOURCE_NAME=$(echo $FINALIZE_RESPONSE | jq -r '.resourceName')
3. Recupera lo stato di caricamento del video
Dopo aver avviato il caricamento di un video, puoi recuperarne lo stato eseguendo una query sulla
you_tube_video_upload risorsa con GAQL:
Java
This example is not yet available in Java; you can take a look at the other languages.
C#
This example is not yet available in C#; you can take a look at the other languages.
PHP
This example is not yet available in PHP; you can take a look at the other languages.
Python
# Retrieve the metadata of the newly uploaded video. query: str = f""" SELECT you_tube_video_upload.resource_name, you_tube_video_upload.video_id, you_tube_video_upload.state FROM you_tube_video_upload WHERE you_tube_video_upload.resource_name = '{video_upload_resource_name}'""" ga_service: GoogleAdsServiceClient = client.get_service("GoogleAdsService") stream: Iterator[SearchGoogleAdsStreamResponse] = ga_service.search_stream( customer_id=customer_id, query=query ) for row in itertools.chain.from_iterable(batch.results for batch in stream): video = row.you_tube_video_upload print( f"Video with ID {row.you_tube_video_upload.video_id} was found in state {row.you_tube_video_upload.state}." )
Ruby
This example is not yet available in Ruby; you can take a look at the other languages.
Perl
This example is not yet available in Perl; you can take a look at the other languages.
curl
curl -i -v -X POST \ "https://qa-prod-googleads.sandbox.googleapis.com/v${API_VERSION}/customers/${CUSTOMER_ID}/googleAds:search" \ --header "Content-Type: application/json" \ --header "Developer-Token: ${DEVELOPER_TOKEN}" \ --header "login-customer-id: ${MANAGER_CUSTOMER_ID}" \ --header "Authorization: Bearer ${OAUTH2_ACCESS_TOKEN}" \ --data @- <<EOF { "query": "SELECT you_tube_video_upload.resource_name, you_tube_video_upload.video_id, you_tube_video_upload.state FROM you_tube_video_upload WHERE you_tube_video_upload.resource_name = '$UPLOADED_VIDEO_RESOURCE_NAME'" } EOF
Gestisci caricamenti
Una volta completato il caricamento di un video, puoi utilizzarlo come asset video.
Utilizza il video caricato
Quando un video raggiunge lo stato PROCESSED, puoi trovare il relativo ID video di YouTube nel campo video_id della risorsa YouTubeVideoUpload.
Utilizza questo video_id per creare un YoutubeVideoAsset con
MutateAssets o collegalo direttamente ai tipi di annunci che supportano i video di YouTube
facendo riferimento all'ID video.
Aggiorna metadati
Puoi aggiornare i metadati di un video caricato tramite questa API utilizzando il metodo UpdateYouTubeVideoUpload. È possibile aggiornare solo i campi video_title, video_description e video_privacy.
Rimuovi i caricamenti
Se devi eliminare i video caricati con l'API Google Ads, utilizza il metodo RemoveYouTubeVideoUpload. Il video verrà rimosso sia dalla raccolta di asset di Google Ads sia da YouTube.