Definir segmentação

Os serviços Opções de segmentação, Opções de segmentação atribuídas e Itens de linha são usados para definir a segmentação de itens de linha na API Display & Video 360. Esta página descreve e dá exemplos de como encontrar opções de segmentação disponíveis, atribuir opções de segmentação a itens de linha e executar operações em massa para listar e editar opções de segmentação atribuídas.

Encontrar opções de segmentação disponíveis

As opções de segmentação usam variáveis especificadas pelo usuário, entidades segmentáveis existentes ou opções pré-existentes para definir o público-alvo desejado. As opções preexistentes são identificadas usando valores de enumeração ou IDs de opção de segmentação, dependendo do tipo de segmentação. As entidades segmentáveis são identificadas usando os respectivos códigos de entidade. Os IDs de opção de segmentação e de entidade podem ser encontrados usando a API Display & Video 360.

Usar valores de enumeração definidos

As opções de segmentação para os seguintes tipos são atribuídas usando tipos de tipo enumerado específicos:

TargetingType Enumerado
TARGETING_TYPE_AGE_RANGE AgeRange
TARGETING_TYPE_CONTENT_INSTREAM_POSITION ContentInstreamPosition
TARGETING_TYPE_CONTENT_OUTSTREAM_POSITION ContentOutstreamPosition
TARGETING_TYPE_DEVICE_TYPE DeviceType
TARGETING_TYPE_DIGITAL_CONTENT_LABEL_EXCLUSION ContentRatingTier
TARGETING_TYPE_ENVIRONMENT Environment
TARGETING_TYPE_EXCHANGE Exchange
TARGETING_TYPE_GENDER Gender
TARGETING_TYPE_HOUSEHOLD_INCOME HouseholdIncome
TARGETING_TYPE_NATIVE_CONTENT_POSITION NativeContentPosition
TARGETING_TYPE_OMID Omid
TARGETING_TYPE_PARENTAL_STATUS ParentalStatus
TARGETING_TYPE_SENSITIVE_CATEGORY_EXCLUSION SensitiveCategory
TARGETING_TYPE_VIDEO_PLAYER_SIZE VideoPlayerSize
TARGETING_TYPE_VIEWABILITY Viewability

Uma versão de string do valor do tipo enumerado relevante pode ser usada para identificar os recursos AssignedTargetingOption atuais desses tipos de segmentação e está disponível no campo assignedTargetingOptionIdAlias. É possível usar esse valor de alias no lugar de assignedTargetingOptionId ao recuperar ou excluir as opções de segmentação atribuídas.

Recuperar IDs de opção de segmentação

Os tipos de segmentação que usam opções preexistentes são atribuídos com base nos IDs de opção de segmentação correspondentes.

Por exemplo, há um número finito de posições na tela que podem ser segmentadas usando o tipo de segmentação TARGETING_TYPE_ON_SCREEN_POSITION. Cada uma dessas posições tem um ID de opção de segmentação correspondente.

É possível recuperar esses IDs de opção de segmentação por meio do serviço Opções de segmentação. Dependendo do tipo de segmentação, a recuperação é feita de duas maneiras:

  • Recuperação individual ou lista completa: a recuperação de opções para a maioria dos tipos de segmentação pode ser feita usando os métodos get e list. Use targetingTypes.targetingOptions.get para recuperar os detalhes de uma opção identificada por um tipo e um ID de opção de segmentação. Use targetingTypes.targetingOptions.list para listar todas as opções de segmentação disponíveis para um determinado tipo.
  • Pesquisa: as opções de tipos de segmentação com base no local (TARGETING_TYPE_GEO_REGION, TARGETING_TYPE_POI e TARGETING_TYPE_BUSINESS_CHAIN) precisam ser recuperadas usando o método search. Use targetingTypes.targetingOptions.search para recuperar opções de segmentação de um determinado tipo que correspondem a determinadas strings de consulta.

Confira um exemplo de como recuperar uma lista de possíveis opções de segmentação para o tipo TARGETING_TYPE_BROWSER:

Java

// Configure the list request.
TargetingOptions.List request =
   service
       .targetingTypes()
       .targetingOptions()
       .list("TARGETING_TYPE_BROWSER")
       .setAdvertiserId(advertiser-id);

// Create the response and nextPageToken variables.
ListTargetingOptionsResponse response;
String nextPageToken = null;

do {
 // Create and execute the list request.
 response = request.setPageToken(nextPageToken).execute();

 // Check if the response is empty.
 if (response.isEmpty()) {
   System.out.print("List request returned no Targeting Options");
   break;
 }

 // Iterate over retrieved targeting options.
 for (TargetingOption option : response.getTargetingOptions()) {
   System.out.printf(
       "Targeting Option ID: %s, Browser Display Name: '%s'\n",
       option.getTargetingOptionId(), option.getBrowserDetails().getDisplayName());
 }

 // Update the next page token.
 nextPageToken = response.getNextPageToken();
} while (!Strings.isNullOrEmpty(nextPageToken));

Python

# Create the page token variable.
next_page_token = ""

while True:
  # Request the targeting options list.
  response = service.targetingTypes() \
    .targetingOptions().list(
      advertiserId=advertiser-id,
      targetingType="TARGETING_TYPE_BROWSER",
      pageToken=next_page_token
  ).execute()

  # Check if response is empty.
  if not response:
    print("List request returned no Targeting Options")
    break

  # Iterate over retrieved targeting options.
  for option in response['targetingOptions']:
    print("Targeting Option ID: %s, Browser Display Name: %s"
          % (option['targetingOptionId'], option['browserDetails']['displayName']))

  # Break out of loop if there is no next page.
  if 'nextPageToken' not in response:
    break

  # Update the next page token.
  next_page_token = response['nextPageToken']

PHP

// Create the page token variable.
$nextPageToken = null;

do {
    // Build the query parameters object for the request.
    $optParams = array(
        'advertiserId' => advertiser-id,
        'pageToken' => $nextPageToken
    );

    // Call the API, getting the browser targeting options for the
    // identified advertiser.
    $response = $this
        ->service
        ->targetingTypes_targetingOptions
        ->listTargetingTypesTargetingOptions(
            'TARGETING_TYPE_BROWSER',
            $optParams
        );

    // Print the resulting targeting options.
    if (!empty($response->getTargetingOptions())) {
        foreach ($response->getTargetingOptions() as $option) {
            printf(
                'Targeting Option ID: %s, Browser Display Name: %s\n',
                $option['targetingOptionId'],
                $option['browserDetails']['displayName']
            );
        }
    } else {
        print('No targeting options returned\n');
    }

    // Update the next page token.
    $nextPageToken = $response->getNextPageToken();
} while (
    !empty($response->getTargetingOptions())
    && $nextPageToken
);

Listar entidades segmentáveis

Para segmentar um item de linha usando uma entidade segmentável existente, você precisa do ID dessa entidade. As entidades segmentáveis, como canais, públicos-alvo combinados e grupos de origem de inventário, podem ser recuperadas usando os próprios serviços na API Display & Video 360.

Cada serviço tem os próprios métodos get e list. Use o método get para confirmar se uma entidade está disponível em um determinado anunciante. Use o método list para descobrir todas as entidades desse tipo de recurso que estão disponíveis para um determinado anunciante e, portanto, que podem ser usadas na atribuição de segmentação a um item de linha nesse anunciante.

Um subconjunto de entidades segmentáveis também pode ser gerenciado por meio da API. Isso é feito pelos métodos create e patch no serviço correspondente, bem como por serviços para os valores individuais listados nas entidades, como origens de inventário, palavras-chave negativas e locais.

Criar códigos de opção de segmentação de PDIs

As opções de segmentação de pontos de interesse nomeados, em TARGETING_TYPE_POI, podem ser recuperadas usando targetingTypes.targetingOptions.search. Além disso, você pode criar IDs de opção de segmentação TARGETING_TYPE_POI personalizados para segmentar coordenadas de latitude e longitude específicas.

Siga estas etapas para criar um ID de opção de segmentação de PDI:

  1. Recuperar coordenadas de latitude/longitude (ex: "40.7414691, -74.003387")
  2. Arredonda os valores das coordenadas para a sexta casa decimal (por exemplo: "40.741469, -74,003387")
  3. Remova as casas decimais dos valores das coordenadas (por exemplo: "40741469, -74003387")
  4. Concatenar os dois valores para formar uma única string, separada por ponto e vírgula (por exemplo: "40741469;-74003387")

A string resultante pode ser usada como um targetingOptionId ao criar uma opção de segmentação atribuída a TARGETING_TYPE_POI.

Após a criação, os campos targetingOptionId e assignedTargetingOptionId do recurso de opção de segmentação atribuído serão atualizados, anexando um ponto e vírgula e hash alfanumérico.

Atribuir uma opção de segmentação

A segmentação atribuída a um item de linha é representada como uma opção de segmentação atribuída. Gerencie essas entidades usando o serviço Opções de segmentação atribuídas. Criar uma opção de segmentação atribuída aplica esses detalhes de segmentação ao item de linha pai. Excluir uma opção de segmentação atribuída remove essa segmentação.

Use advertisers.lineItems.targetingTypes.assignedTargetingOptions.create para criar opções de segmentação atribuídas. Especifique os parâmetros de segmentação no campo details do recurso da opção de segmentação atribuído que corresponde ao tipo de segmentação pretendido.

Veja um exemplo de como criar uma opção de segmentação atribuída do tipo de segmentação TARGETING_TYPE_BROWSER:

Java

// Create an AssignedTargetingOption object of the
// browser targeting type.
AssignedTargetingOption assignedTargetingOption =
   new AssignedTargetingOption()
       .setBrowserDetails(
           new BrowserAssignedTargetingOptionDetails()
               .setTargetingOptionId(targeting-option-id));

// Configure the create request.
AssignedTargetingOptions.Create request =
   service
       .advertisers()
       .lineItems()
       .targetingTypes()
       .assignedTargetingOptions()
       .create(
           advertiser-id,
           line-item-id,
           "TARGETING_TYPE_BROWSER",
           assignedTargetingOption);

// Send the request.
AssignedTargetingOption response = request.execute();

// Display the new assigned targeting option.
System.out.printf("AssignedTargetingOption %s was created.",
   response.getName());

Python

# Create a assigned targeting option object.
assigned_targeting_option_obj = {
    'browserDetails': {
        'targetingOptionId': targeting-option-id
    }
}

# Create the assigned targeting option.
assigned_targeting_option = service.advertisers().lineItems()\
  .targetingTypes().assignedTargetingOptions().create(
    advertiserId=advertiser-id,
    lineItemId=line-item-id,
    targetingType="TARGETING_TYPE_BROWSER",
    body=assigned_targeting_option_obj
).execute()

# Display the new assigned targeting option.
print("Assigned Targeting Option %s was created."
      % assigned_targeting_option["name"])

PHP

// Create a assigned targeting option object.
$assignedTargetingOption =
    new Google_Service_DisplayVideo_AssignedTargetingOption();

// Create and set browser details.
$details =
    new Google_Service_DisplayVideo_BrowserAssignedTargetingOptionDetails();
$details->setTargetingOptionId(targeting-option-id);
$assignedTargetingOption->setBrowserDetails($details);

// Call the API, creating the browser assigned targeting option for the
// given line item.
$result = $this
    ->service
    ->advertisers_lineItems_targetingTypes_assignedTargetingOptions
    ->create(
        advertiser-id,
        line-item-id,
        'TARGETING_TYPE_BROWSER',
        $assignedTargetingOption
    );

printf(
    'Assigned Targeting Option %s was created.\n',
    $result['name']
);

Erros

Erros de configuração de segmentação

Há várias regras complexas sobre segmentação no Display & Video 360. Eles são aplicados na API Display & Video 360 por erros retornados na criação da opção de segmentação atribuída. O erro retornado pela API especificará a violação.

Os erros são causados principalmente por uma segmentação existente atribuída a um item de linha. Use advertisers.lineItems.targetingTypes.assignedTargetingOptions.list para recuperar todas as opções de um determinado tipo atribuído a um item de linha, avalie se a segmentação desejada é possível devido às limitações e use advertisers.lineItems.targetingTypes.assignedTargetingOptions.delete para remover qualquer segmentação indesejada antes de tentar criar a opção de segmentação atribuída desejada.

Erros de segmentação do YouTube e parceiros

Não é possível atualizar a segmentação específica de campanhas do YouTube e parceiros usando a API Display & Video 360. Se você tentar fazer isso, ocorrerá um erro.

A segmentação do YouTube e parceiros consiste em toda segmentação atribuída diretamente a itens de linha e grupos de anúncios do YouTube e parceiros, além de qualquer segmentação dos seguintes tipos:

  • TARGETING_TYPE_SESSION_POSITION
  • TARGETING_TYPE_YOUTUBE_CHANNEL
  • TARGETING_TYPE_YOUTUBE_VIDEO

Erros de simultaneidade

A tentativa de atualizar as configurações ou a segmentação de um único item de linha por meio de várias solicitações simultâneas resulta em erro.

Se você precisar adicionar ou remover várias opções de segmentação atribuídas a um único item de linha ao mesmo tempo, use uma solicitação de edição em massa. Se você quiser atualizar as configurações e a segmentação de um item de linha, faça a solicitação advertisers.lineItems.patch e a solicitação de segmentação relevante consecutivamente para garantir que a segunda solicitação não seja enviada até que a primeira retorne uma resposta.

Operações de segmentação em massa e em todo o recurso

Você pode usar métodos de segmentação em massa e em todo o recurso para gerenciar as opções de segmentação atribuídas em todos os tipos de segmentação:

Se você quiser ter uma visão completa da segmentação atual de um item de linha, aplicar uma configuração de segmentação predefinida a um item de linha ou fazer várias mudanças simultaneamente na segmentação de um item de linha, use esses métodos de segmentação.

Segmentação de lista em massa

O advertisers.lineItems.bulkListAssignedTargetingOptions oferece uma maneira de analisar toda a segmentação atribuída a um ou mais itens de linha em diferentes tipos de segmentação. Ele opera de forma semelhante a qualquer outro método list. É possível usar o parâmetro de consulta filter para filtrar os resultados por TargetingType ou Inheritance.

Veja um exemplo de como listar todas as opções de segmentação atribuídas a um item de linha herdado pelo parceiro ou anunciante pai:

Java

// Configure the bulk list request.
LineItems.BulkListAssignedTargetingOptions request =
    service.advertisers().lineItems()
        .bulkListAssignedTargetingOptions(advertiser-id);

// Set Line Items to retrieve targeting for.
request.setLineItemIds(line-item-ids);

// Set filter to only return inherited assigned targeting options.
request.setFilter(
    "inheritance=\"INHERITED_FROM_ADVERTISER\" OR inheritance=\"INHERITED_FROM_PARTNER\"");

// Create the response and nextPageToken variables.
BulkListAssignedTargetingOptionsResponse response;
String nextPageToken = null;

do {
  // Set page token and execute the list request.
  response = request.setPageToken(nextPageToken).execute();

  // Check if the response is empty.
  if (response.isEmpty()) {
    System.out.print("Bulk list request returned no Assigned Targeting Options");
    break;
  }

  // Iterate over retrieved line item assigned targeting option wrapper objects.
  for (LineItemAssignedTargetingOption lineItemAssignedTargetingOption
      : response.getLineItemAssignedTargetingOptions()) {
    System.out.printf(
        "Assigned Targeting Option %s found\n",
        lineItemAssignedTargetingOption.getAssignedTargetingOption().getName());
  }

  // Update the next page token.
  nextPageToken = response.getNextPageToken();
} while (!Strings.isNullOrEmpty(nextPageToken));

Python

# Create the page token variable.
next_page_token = ""

while True:
  # Execute the list request.
  response = service.advertisers().lineItems() \
    .bulkListAssignedTargetingOptions(
      advertiserId=advertiser-id,
      lineItemIds=line-item-ids,
      filter="inheritance=\"INHERITED_FROM_ADVERTISER\" OR "
             "inheritance=\"INHERITED_FROM_PARTNER\"",
      pageToken=next_page_token
  ).execute()

  # Check if response is empty.
  if not response:
    print("Bulk list request returned no Assigned Targeting Options")
    break

  # Iterate over retrieved assigned targeting options.
  for lineItemAssignedTargetingOption in response['lineItemAssignedTargetingOptions']:
    print("Assigned Targeting Option %s found"
          % (lineItemAssignedTargetingOption['assignedTargetingOption']['name']))

  # Break out of loop if there is no next page.
  if 'nextPageToken' not in response:
    break

  # Update the next page token.
  next_page_token = response['nextPageToken']

PHP

// Create the page token variable.
$nextPageToken = null;

do {
    // Build the query parameters object for the request.
    $optParams = array(
        'lineItemIds' => line-item-ids,
        'filter' => "inheritance=\"INHERITED_FROM_ADVERTISER\" OR "
            . "inheritance=\"INHERITED_FROM_PARTNER\"",
        'pageToken' => $nextPageToken
    );

    // Call the API, getting all the assigned targeting options for the
    // identified line item.
    $response = $service
        ->advertisers_lineItems
        ->bulkListAssignedTargetingOptions(
            advertiser-id,
            $optParams
    );

    // Print the returned assigned targeting options.
    if (!empty($response->getLineItemAssignedTargetingOptions())) {
        foreach ($response->getLineItemAssignedTargetingOptions() as $option) {
            printf('Assigned Targeting Option %s found\n', $option->getAssignedTargetingOption()['name']);
        }
    } else {
        print('No targeting options returned\n');
    }

    // Update the next page token.
    $nextPageToken = $response->getNextPageToken();
} while (
    !empty($response->getLineItemAssignedTargetingOptions())
    && $nextPageToken);

Editar segmentação em massa

advertisers.lineItems.bulkEditAssignedTargetingOptions oferece uma maneira de adicionar e remover várias opções de segmentação de diversos tipos de um ou mais itens de linha simultaneamente.

O método usa uma lista de DeleteAssignedTargetingOptionsRequests e uma lista de CreateAssignedTargetingOptionsRequests. Um único objeto de solicitação pode representar a exclusão ou criação de várias opções de segmentação atribuídas do mesmo tipo de segmentação.

Se a tentativa de exclusão ou criação de uma opção de segmentação atribuída causar um erro para um item de linha, a ação em massa será abandonada para esse item de linha. A solicitação retorna uma lista de itens de linha atualizados, bem como listas dos itens de linha que não foram atualizados e dos erros relevantes.

Veja um exemplo de como editar em massa as opções de segmentação atribuídas para um ou mais itens de linha com listas de opções de segmentação atribuídas para exclusão e opções de segmentação para criar:

Java

// Create a bulk edit request.
BulkEditAssignedTargetingOptionsRequest requestContent =
    new BulkEditAssignedTargetingOptionsRequest();

// Set line item IDs in edit request.
requestContent.setLineItemIds(line-item-ids);

// Build delete request list.
ArrayList<DeleteAssignedTargetingOptionsRequest> deleteRequests =
    new ArrayList<DeleteAssignedTargetingOptionsRequest>();

// Add browser assigned targeting option IDs to delete request list.
deleteRequests.add(new DeleteAssignedTargetingOptionsRequest()
    .setTargetingType("TARGETING_TYPE_BROWSER")
    .setAssignedTargetingOptionIds(delete-browser-assigned-targeting-ids));

// Add device make or model assigned targeting option IDs to delete request list.
deleteRequests.add(new DeleteAssignedTargetingOptionsRequest()
    .setTargetingType("TARGETING_TYPE_DEVICE_MAKE_MODEL")
    .setAssignedTargetingOptionIds(
        delete-device-make-model-assigned-targeting-ids));

// Set delete requests in edit request.
requestContent.setDeleteRequests(deleteRequests);

// Build create request list.
ArrayList<CreateAssignedTargetingOptionsRequest> createRequests =
    new ArrayList<CreateAssignedTargetingOptionsRequest>();

// Create browser assigned targeting option create request.
CreateAssignedTargetingOptionsRequest createBrowserTargetingRequest =
    new CreateAssignedTargetingOptionsRequest();
createBrowserTargetingRequest.setTargetingType("TARGETING_TYPE_BROWSER");

// Create and set list of browser assigned targeting options.
ArrayList<AssignedTargetingOption> createBrowserAssignedTargetingOptions =
    new ArrayList<AssignedTargetingOption>();
for (String targetingOptionId : create-browser-assigned-targeting-ids) {
  createBrowserAssignedTargetingOptions.add(new AssignedTargetingOption()
      .setBrowserDetails(
          new BrowserAssignedTargetingOptionDetails()
              .setTargetingOptionId(targetingOptionId)));
}
createBrowserTargetingRequest
    .setAssignedTargetingOptions(createBrowserAssignedTargetingOptions);

// Add browser assigned targeting options to list of create requests.
createRequests.add(createBrowserTargetingRequest);

// Set create requests in edit request.
requestContent.setCreateRequests(createRequests);

// Configure the bulk edit request.
LineItems.BulkEditAssignedTargetingOptions request =
    service.advertisers().lineItems()
        .bulkEditAssignedTargetingOptions(
            advertiser-id,
            requestContent);

// Execute bulk edit request.
BulkEditAssignedTargetingOptionsResponse response = request.execute();

// Check if any line items updated successfully.
if (response.getUpdatedLineItemIds() == null || response.getUpdatedLineItemIds().isEmpty()) {
  System.out.println("No line items were updated successfully.");
} else {
  System.out.printf(
      "Targeting configurations for the following line item IDs were updated: %s.\n",
      Arrays.toString(response.getUpdatedLineItemIds().toArray()));
}

// Check if any line items failed to update.
if (response.getFailedLineItemIds() == null || response.getFailedLineItemIds().isEmpty()) {
  System.out.println("No line items failed to update.");
} else {
  // Print the line items that failed to update.
  System.out.printf(
      "Targeting configurations for the following line item IDs failed to update: %s.\n",
      Arrays.toString(response.getFailedLineItemIds().toArray()));

  // Print errors thrown for failed updates.
  System.out.println("The failed updates were caused by the following errors:");
  for (Status error : response.getErrors()) {
    System.out.printf("Error Code: %s, Message: %s\n", error.getCode(), error.getMessage());
  }
}

Python

# Build assigned targeting option objects to create.
createBrowserAssignedTargetingOptions = []
for targeting_id in create-browser-assigned-targeting-ids:
  createBrowserAssignedTargetingOptions.append(
      {'browserDetails': {'targetingOptionId': targeting_id}}
  )

# Create a bulk edit request.
bulk_edit_line_item_request = {
    'lineItemIds': line-item-ids,
    'deleteRequests': [
        {
            'targetingType': 'TARGETING_TYPE_BROWSER',
            'assignedTargetingOptionIds':
              delete-browser-assigned-targeting-ids
        },
        {
            'targetingType': 'TARGETING_TYPE_DEVICE_MAKE_MODEL',
            'assignedTargetingOptionIds':
              delete-device-make-model-assigned-targeting-ids
        }
    ],
    'createRequests': [
        {
            'targetingType': 'TARGETING_TYPE_BROWSER',
            'assignedTargetingOptions':
              createBrowserAssignedTargetingOptions
        }
    ]
}

# Edit the line item targeting.
response = service.advertisers().lineItems()\
  .bulkEditAssignedTargetingOptions(
    advertiserId=advertiser-id,
    body=bulk_edit_line_item_request
).execute()

# Print successfully updated line items.
if 'updatedLineItemIds' not in response:
  print("No line items were updated successfully.")
else:
  print("Targeting configurations for the following line item IDs were updated: %s"
        % response['updatedLineItemIds'])

# Print line items that failed to update.
if 'failedLineItemIds' not in response:
  print("No line items failed to update.")
else:
  print("Targeting configurations for the following line item IDs failed to update: %s"
        % response['failedLineItemIds'])
  if 'errors' in response:
    print("The failed updates were caused by the following errors:")
    for error in response["errors"]:
      print("Error code: %s, Message: %s" % (error["code"], error["message"]))

PHP

// Create delete request list.
$deleteRequests = array();

// Create and add browser assigned targeting option IDs to delete request list.
$deleteBrowserTargetingRequest =
    new Google_Service_DisplayVideo_DeleteAssignedTargetingOptionsRequest();
$deleteBrowserTargetingRequest->setTargetingType(
    "TARGETING_TYPE_BROWSER"
);
$deleteBrowserTargetingRequest->setAssignedTargetingOptionIds(
    delete-browser-assigned-targeting-ids
);
$deleteRequests[] = $deleteBrowserTargetingRequest;

// Create and add device assigned targeting option IDs to delete request list.
$deleteDeviceTargetingRequest =
    new Google_Service_DisplayVideo_DeleteAssignedTargetingOptionsRequest();
$deleteDeviceTargetingRequest->setTargetingType(
    "TARGETING_TYPE_DEVICE_MAKE_MODEL"
);
$deleteDeviceTargetingRequest->setAssignedTargetingOptionIds(
    delete-device-make-model-assigned-targeting-ids
);
$deleteRequests[] = $deleteDeviceTargetingRequest;

// Create create request list.
$createRequests = array();

// Create and populate list of browser assigned targetion options to create.
$createBrowserAssignedTargetingOptions = array();
foreach (create-browser-assigned-targeting-ids as $optionId) {
    $option = new Google_Service_DisplayVideo_AssignedTargetingOption();
    $details =
        new Google_Service_DisplayVideo_BrowserAssignedTargetingOptionDetails();
    $details->setTargetingOptionId($optionId);

    $option->setBrowserDetails($details);
    $createBrowserAssignedTargetingOptions[] = $option;
}

// Create and add browser assigned targeting option create request to create
// request list.
$createBrowserTargetingRequest =
    new Google_Service_DisplayVideo_CreateAssignedTargetingOptionsRequest();
$createBrowserTargetingRequest->setTargetingType(
    "TARGETING_TYPE_BROWSER"
);
$createBrowserTargetingRequest->setAssignedTargetingOptions(
    $createBrowserAssignedTargetingOptions
);
$createRequests[] = $createBrowserTargetingRequest;

// Create a bulk edit request and assign create and delete request lists.
$body =
    new Google_Service_DisplayVideo_BulkEditAssignedTargetingOptionsRequest();
$body->setLineItemIds(line-item-ids);
$body->setCreateRequests($createRequests);
$body->setDeleteRequests($deleteRequests);

// Call the API, editing the assigned targeting options for the identified
// line item.
$response = $service
    ->advertisers_lineItems
    ->bulkEditAssignedTargetingOptions(
        advertiser-id,
        $body
    );

// Print successfully updated line items.
if (!empty($response->getUpdatedLineItemIds())) {
    printf('Targeting configurations for the following line item IDs were updated:\n');
    foreach ($response->getUpdatedLineItemIds() as $id) {
        printf('%s\n', $id);
    }
} else {
    print('No line items were updated successfully.\n');
}

// Print line items that failed to update.
if (!empty($response->getFailedLineItemIds())) {
    print('Targeting configurations for the following line item IDs failed to update:\n');
    foreach ($response->getFailedLineItemIds() as $id) {
        printf('%s\n', $id);
    }
    print('The failed updates were caused by the following errors:\n');
    foreach ($response->getErrors() as $error) {
        printf('Error Code: %s, Message: %s\n', $error->getCode(), $error->getMessage());
    }
} else {
    print('No line items failed to update.\n');
}