Как запрашивать показатели видимости и недействительного трафика

Общие сведения

В этой статье рассказывается, как с помощью API составлять запросы для действительного трафика (видимости) и недействительного трафика. Эти показатели доступны только для инвентаря, закупленного через Google Рекламу, Дисплей и Видео 360 и YouTube Резерв.

Для сбора аккредитованных MRC показателей просмотров TrueView требуется ADH API, поскольку шаблона такого запроса не существует. Учитывайте, что показатели просмотров TrueView – не то же самое, что показатели видимости.

Выберите сервис покупки рекламы, для которого вы хотите составить запрос показателей видимости.

Как составить запрос показателей видимости в интерфейсе

Этот шаблон запроса видимости позволяет получить показатели, аккредитованные MRC.

Аккредитация MRC имеет только два варианта: ее можно получить или не получить. Она применяется ко всей таблице. В BigQuery аккредитованные MRC результаты помечаются ярлыком adh-mrc-accredited. Чтобы получить аккредитацию MRC, необходимо выполнить запрос в шаблоне.

Чтобы выполнить аккредитованный MRC запрос в шаблоне, сделайте следующее:

  1. Создайте запрос, выбрав в качестве сервиса покупки рекламы YouTube Reserve, а в качестве шаблона запроса – Видимость видеообъявлений.
  2. Рядом с Использовать шаблон нажмите кнопку Выполнить.

Как запросить показатели недействительного трафика и видимости через API

Показатели недействительного трафика и видимости можно получать с помощью ADH API, используя конечные точки generateIvtReport и startAnalysis. Показатели недействительного трафика необходимо извлекать с помощью generateIvtReport , чтобы показатели получили аккредитацию MRC и был применен ярлык adh-mrc-accredited. Приведенный ниже глобальный запрос также должен использоваться для показателей видимости через ADH API, чтобы получить аккредитацию MRC. В этом разделе рассказывается, как отправить запрос в эту конечную точку, используя клиентскую библиотеку Python.

Инструкции по настройке и авторизации/аутентификации вы найдете в кратком руководстве по API.

Укажите в перечисленных ниже полях данные вашего аккаунта и выполните запрос, чтобы получить отчет о недействительном трафике для кампаний YouTube Reserve .

  • Секретный код клиента.
  • Идентификатор клиента.
  • Ключ API.
  • Order IDs
  • Часовой пояс.

Пример кода

from __future__ import print_function
import json
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

# If modifying these scopes, delete the file `token.json`.
SCOPES
= ['https://www.googleapis.com/auth/adsdatahub']
TOKEN_FILE
= 'token.json'

creds
= None

# The file token.json 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_FILE):
    creds
= Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
# 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(
           
'YOUR_CLIENT_SECRETS.json', SCOPES)
        creds
= flow.run_local_server(port=0)
   
# Save the credentials for the next run.
   
with open(TOKEN_FILE, 'w') as token:
        token
.write(creds.to_json())

service
= build('adsdatahub', 'v1', credentials=creds,
                developerKey
='YOUR_API_KEY',
                discoveryServiceUrl
='https://adsdatahub.googleapis.com/$discovery/rest?version=v1&labels=')

body
= {
   
'ads_data_customer_id': YOUR_CUSTOMER_ID,
   
'start_date': {
       
'year': 2019,
       
'month': 12,
       
'day': 15
   
},
   
'end_date': {
       
'year': 2019,
       
'month': 12,
       
'day': 20
   
},
   
'time_zone': 'YOUR_TIMEZONE',
   
'yt_reserve_dimensions': {
       
'order_ids': [YOUR_ORDER_IDS],
       
'metric_type': 'METRIC_TYPE_IMPRESSION'
   
},
   
'dest_table': 'YOUR_DESTINATION_TABLE'
}

resp
= service.customers().generateIvtReport(name='customers/YOUR_CUSTOMER_ID,
                                             body=body).execute()
print(json.dumps(resp))
from __future__ import print_function
import json
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

# If modifying these scopes, delete the file `token.json`.
SCOPES
= ['https://www.googleapis.com/auth/adsdatahub']
TOKEN_FILE
= 'token.json'

creds
= None

# The file token.json 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_FILE):
    creds
= Credentials.from_authorized_user_file(TOKEN_FILE, SCOPES)
# 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(
           
'YOUR_CLIENT_SECRETS.json', SCOPES)
        creds
= flow.run_local_server(port=0)
   
# Save the credentials for the next run.
   
with open(TOKEN_FILE, 'w') as token:
        token
.write(creds.to_json())

service
= build('adsdatahub', 'v1', credentials=creds,
                developerKey
='YOUR_API_KEY',
                discoveryServiceUrl
='https://adsdatahub.googleapis.com/$discovery/rest?version=v1&labels=')

name
= 'customers/global/analysisQueries/ad88e8562a8f4baa9c8522945fe95522'
body
= {
 
'spec': {
   
'ads_data_customer_id': YOUR_CUSTOMER_ID,
   
'start_date': {
     
'year': 2019,
     
'month': 12,
     
'day': 15
   
},
   
'end_date': {
     
'year': 2019,
     
'month': 12,
     
'day': 20
   
},
   
'time_zone': 'YOUR_TIMEZONE',
   
'parameter_values': {
     
'line_item_ids': {
       
'array_value': {
         
'values': [
           
{
             
'value': 'YOUR_LINE_ITEM_ID'
           
},
         
]
       
}
     
}
   
}
 
},
 
'dest_table': 'YOUR_DESTINATION_TABLE',
 
'customer_id': YOUR_CUSTOMER_ID
}

resp
= service.customers().analysisQueries().start(name=name,body=body).execute()
print(json.dumps(resp))