Переход с SOAP API Менеджера рекламы

The Ad Manager SOAP API is a legacy API for reading and writing your Ad Manager data and running reports. If you can migrate, we recommend using the Ad Manager API (Beta). However, Ad Manager SOAP API versions are supported for their typical lifecycle. For more information, see the Ad Manager SOAP API Deprecation Schedule .

В данном руководстве описаны различия между SOAP API менеджера рекламы и API менеджера рекламы (бета-версия).

Учиться

The standard Ad Manager SOAP API service methods have equivalent concepts in the Ad Manager API. The Ad Manager API also has methods for reading single entities. The following table shows an example mapping for Order methods:

метод SOAP REST-методы
getOrdersByStatement networks.orders.get
networks.orders.list

Аутентификация

To authenticate with the Ad Manager API (Beta), you can use your existing Ad Manager SOAP API credentials or create new ones. With either option, you must first enable the Ad Manager API in your Google Cloud project. For more details, see Authentication .

If you are using a client library, set up application default credentials by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS to the path of your service account key file. For more details, see How Application Default Credentials works .

Если вы используете учетные данные установленного приложения, создайте JSON-файл в следующем формате и установите переменную среды, указав вместо этого путь к нему:

{
  "client_id": "CLIENT_ID",
  "client_secret": "CLIENT_SECRET",
  "refresh_token": "REFRESH_TOKEN",
  "type": "authorized_user"
}

Замените следующие значения:

  • CLIENT_ID : Ваш новый или существующий идентификатор клиента.
  • CLIENT_SECRET : Ваш новый или существующий секретный ключ клиента.
  • REFRESH_TOKEN : Ваш новый или существующий токен обновления.

Linux или macOS

export GOOGLE_APPLICATION_CREDENTIALS=KEY_FILE_PATH

Windows

set GOOGLE_APPLICATION_CREDENTIALS=KEY_FILE_PATH

Разберитесь в различиях фильтров.

Язык запросов API Ad Manager (бета-версия) поддерживает все функции языка запросов издателя (PQL), но существуют существенные синтаксические различия.

This example for listing Order objects illustrates the major changes such as the removal of bind variables, case sensitive operators, and the replacement of ORDER BY and LIMIT clauses with separate fields:

SOAP API менеджера рекламы

<filterStatement>
  <query>WHERE name like "PG_%" and lastModifiedDateTime &gt;= :lastModifiedDateTime ORDER BY id ASC LIMIT 500</query>
  <values>
    <key>lastModifiedDateTime</key>
    <value xmlns:ns2="https://www.google.com/apis/ads/publisher/v202502" xsi:type="ns2:DateTimeValue">
      <value>
        <date>
          <year>2024</year>
          <month>1</month>
          <day>1</day>
        </date>
        <hour>0</hour>
        <minute>0</minute>
        <second>0</second>
        <timeZoneId>America/New_York</timeZoneId>
      </value>
    </value>
  </values>
</filterStatement>

API менеджера рекламы (бета-версия)

формат JSON

{
  "filter": "displayName = \"PG_*\" AND updateTime > \"2024-01-01T00:00:00-5:00\"",
  "pageSize": 500,
  "orderBy":  "name"
}

URL-кодированный

GET https://admanager.googleapis.com/v1/networks/123/orders?filter=displayName+%3D+\"PG_*\"+AND+updateTime+%3E+\"2024-01-01T00%3A00%3A00-5%3A00\"

API Ad Manager (бета-версия) поддерживает все возможности PQL, но отличается от SOAP API Ad Manager следующим синтаксисом:

  • The operators AND and OR are case sensitive in the Ad Manager API (Beta). Lowercase and and or are treated as bare literal search strings, a feature in the Ad Manager API (Beta) to search across fields.

    Используйте операторы в верхнем регистре.

    // Matches unarchived Orders where order.notes has the value 'lorem ipsum'.
    notes = "lorem ipsum" AND archived = false
    

    Строчные буквы рассматриваются как буквальные.

    // Matches unarchived Orders where order.notes has the value 'lorem ipsum'
    // and any field in the order has the literal value 'and'.
    notes = "lorem ipsum" and archived = false
    
  • Символ * является подстановочным знаком для сопоставления строк. API Ad Manager (бета-версия) не поддерживает оператор like .

    Менеджер рекламы SOAP API PQL

    // Matches orders where displayName starts with the string 'PG_'
    displayName like "PG_%"
    

    API менеджера рекламы (бета-версия)

    // Matches orders where displayName starts with the string 'PG_'
    displayName = "PG_*"
    
  • Названия полей должны располагаться слева от оператора сравнения:

    Действительный фильтр

    updateTime > "2024-01-01T00:00:00Z"
    

    Неверный фильтр

    "2024-01-01T00:00:00Z" < updateTime
    
  • API Ad Manager (бета-версия) не поддерживает переменные привязки. Все значения должны быть встроены непосредственно в код.

  • Строковые литералы, содержащие пробелы, должны быть заключены в двойные кавычки, например, "Foo bar" . Одинарные кавычки для заключения строковых литералов недопустимы.

Удалить сортировку по пунктам

Specifying a sorting order is optional in the Ad Manager API (Beta). If you want to specify a sorting order for your result set, remove the PQL ORDER BY clause and set the orderBy field instead:

GET networks/${NETWORK_CODE}/orders?orderBy=updateTime+desc

Переход от смещений к токенам пагинации

API Ad Manager (бета-версия) использует токены пагинации вместо операторов LIMIT и OFFSET для постраничного просмотра больших наборов результатов.

The Ad Manager API (Beta) uses a pageSize parameter to control the page size. Unlike the LIMIT clause in the Ad Manager SOAP API, omitting a page size does not return the entire result set. Instead, the list method uses a default page size of 50 . The following example sets pageSize and pageToken as URL parameters:

# Initial request
GET networks/${NETWORK_CODE}/orders?pageSize=50

# Next page
GET networks/${NETWORK_CODE}/orders?pageSize=50&pageToken=${TOKEN_FROM_INITIAL_REQUEST}

Unlike the Ad Manager SOAP API, the Ad Manager API (Beta) may return fewer results than the requested page size even if there are additional pages. Use the nextPageToken field to determine if there are additional results.

Although an offset is not required for pagination, you may use the skip field for multithreading. When multithreading, use the pagination token from the first page to ensure you are reading from the same result set:

# First thread
GET networks/${NETWORK_CODE}/orders?pageSize=50&pageToken=${TOKEN_FROM_INITIAL_REQUEST}

# Second thread
GET networks/${NETWORK_CODE}/orders?pageSize=50&pageToken=${TOKEN_FROM_INITIAL_REQUEST}&skip=50

Миграционные отчеты

API SOAP позволяет читать и запускать отчеты только в устаревшем инструменте «Отчеты». В свою очередь, API REST позволяет читать, записывать и запускать только интерактивные отчеты.

Инструменты создания отчетов и API используют разные пространства идентификаторов . Идентификатор объекта SavedQuery в SOAP API нельзя использовать в REST API.

If you are using SavedQuery , you can migrate the report to an Interactive report in the UI and create a mapping between the two ID spaces. For more information about migrating reports in the UI, see Migrate reports to Interactive reports .

Полное сопоставление значений перечислений SOAP и REST см. в справочнике по отчетам .

Разберитесь в различиях API.

Существуют некоторые различия в том, как SOAP API и REST API обрабатывают определения отчетов и результаты:

  • The SOAP API automatically added a corresponding ID dimension to the results when a report only requested the NAME . In the REST API, you must explicitly add the ID dimension to the ReportDefinition for it to be included in the results.

  • The SOAP API did not have explicit types for metrics. The REST API defines a data type, documented on the Dimension enum value. Note that ENUM dimensions are open enums . You must handle new and unknown enum values when parsing results.

  • В SOAP API разделялись Dimensions и DimensionAttributes ). В REST API используется унифицированное перечисление Dimension , содержащее оба типа данных.

  • The SOAP API did not have a limit on the number of dimensions. Interactive Reports have a limit of 10 dimensions in both the UI and API. Dimensions that break down by the same ID space are counted as a single dimension. For example, including ORDER_NAME , ORDER_ID , and ORDER_START_DATE only counts as 1 dimension when calculating the limit.