Os serviços Targeting Options, Assigned Targeting Options e Line items são usados em conjunto para definir a segmentação de itens de linha na API do Display & Video 360. Esta página descreve e mostra exemplos de como encontrar as opções de segmentação disponíveis, atribuir opções de segmentação a itens de linha e executar operações em massa em itens de linha para listar e editar as opções de segmentação atribuídas.
Encontrar as opções de segmentação disponíveis
As opções de segmentação usam variáveis especificadas pelo usuário, entidades segmentáveis ou opções preexistentes para definir o público-alvo desejado. As opções pré-existentes são identificadas usando valores de tipo enumerado ou IDs de opção de segmentação, dependendo do tipo de segmentação. As entidades segmentáveis são identificadas usando os IDs delas. Os IDs de opções de segmentação e de entidade podem ser encontrados usando a API Display & Video 360.
Usar valores de tipo enumerado
As opções de segmentação para os seguintes tipos são atribuídas usando tipos de enumeração específicos:
TargetingType |
Enumeração |
---|---|
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 recursos
AssignedTargetingOption
existentes desses tipos de segmentação e está
disponível no campo assignedTargetingOptionIdAlias
. É possível
usar esse valor de alias no lugar de assignedTargetingOptionId
ao
extrair ou excluir opções de segmentação atribuídas.
Extrair IDs de opções de segmentação
Os tipos de segmentação que usam opções preexistentes são atribuídos usando os IDs de opções 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.
Esses IDs podem ser recuperados pelo serviço de opções de segmentação. Dependendo do tipo de segmentação, a recuperação é feita de uma destas duas maneiras:
- Extração individual ou lista exaustiva: a extração de opções para a
maioria dos tipos de segmentação pode ser feita usando os métodos
get
elist
. UsetargetingTypes.targetingOptions.get
para recuperar os detalhes de uma opção de segmentação identificada por um tipo e um ID de opção de segmentação. UsetargetingTypes.targetingOptions.list
para listar todas as opções de segmentação disponíveis de um determinado tipo. - Pesquisa: as opções para tipos de segmentação por local
(
TARGETING_TYPE_GEO_REGION
,TARGETING_TYPE_POI
eTARGETING_TYPE_BUSINESS_CHAIN
) precisam ser recuperadas usando o métodosearch
. UsetargetingTypes.targetingOptions.search
para recuperar opções de segmentação de um determinado tipo que correspondem às 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, você precisa do ID dela. As entidades segmentáveis, como canais, públicos-alvo combinados e grupos de origem de inventário, podem ser recuperadas pelos 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, podem ser usadas para atribuir a segmentação a um
item de linha desse anunciante.
Um subconjunto de entidades segmentáveis também pode ser gerenciado pela API. Isso é feito
usando os métodos create
e patch
no serviço correspondente, além
de serviços para os valores individuais listados nas entidades, como
fontes de inventário,
palavras-chave negativas e
localizações.
Criar IDs de opções de segmentação por PDI
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, é possível criar IDs de opções 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 ponto de interesse:
- Extrair coordenadas de latitude e longitude (por exemplo, "40.7414691, -74.003387")
- Arredondar os valores das coordenadas para a sexta casa decimal (por exemplo, "40,741469, -74,003387")
- Remova as casas decimais dos valores das coordenadas (por exemplo, "40741469, -74003387").
- Concatenar os dois valores para criar 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 um 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. É possível gerenciar essas entidades usando o serviço Atribuição de opções de segmentação. A criação de uma opção de segmentação atribuída aplica esses detalhes ao item de linha pai. A exclusão de uma opção de segmentação atribuída atual 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 de opção de segmentação atribuído que corresponde ao tipo de segmentação pretendido.
Confira um exemplo de como criar uma opção de segmentação atribuída do tipo 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 da segmentação
Há várias regras complexas relacionadas à segmentação no Display & Video 360. Elas são aplicadas na API Display & Video 360 por erros retornados na criação de opções de segmentação atribuídas. O erro retornado pela API vai especificar a violação.
A maioria dos erros é causada por segmentações atribuídas a um item de linha. Use
advertisers.lineItems.targetingTypes.assignedTargetingOptions.list
para recuperar todas as opções de segmentação de um determinado tipo atribuído a um item de linha, avaliar se a segmentação desejada é possível considerando as limitações e usar
advertisers.lineItems.targetingTypes.assignedTargetingOptions.delete
para remover qualquer segmentação indesejada antes de tentar criar a opção de segmentação atribuída.
Erros de segmentação do YouTube e parceiros
A segmentação específica para campanhas do YouTube e parceiros não pode ser atualizada usando a API do Display & Video 360. Se você tentar fazer isso, vai receber um erro.
A segmentação do YouTube e parceiros consiste em toda a segmentação atribuída diretamente a itens de linha do YouTube e parceiros e grupos de anúncios, além de qualquer segmentação dos seguintes tipos:
TARGETING_TYPE_SESSION_POSITION
TARGETING_TYPE_YOUTUBE_CHANNEL
TARGETING_TYPE_YOUTUBE_VIDEO
Erros de simultaneidade
Tentar atualizar as configurações ou a segmentação de um único item de linha por meio de várias solicitações simultâneas vai resultar em um erro.
Se você precisar adicionar ou remover várias opções de segmentação atribuídas para 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 de forma consecutiva 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 os 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:
- Use os métodos de segmentação em massa para recuperar ou editar opções de segmentação em vários tipos e recursos. É possível recuperar as
configurações completas de segmentação de vários itens de linha usando
advertisers.lineItems.bulkListAssignedTargetingOptions
ou fazer atualizações idênticas à segmentação em vários itens de linha usandoadvertisers.lineItems.bulkEditAssignedTargetingOptions
. Elas estão disponíveis apenas no serviçoadvertisers.lineItems
. - Use os métodos de segmentação em todo o recurso para recuperar ou editar opções de segmentação em vários tipos de segmentação em um único recurso. Eles estão disponíveis
nos serviços
partners
eadvertisers
e são nomeadoslistAssignedTargetingOptions
oueditAssignedTargetingOptions
.
Se você quiser uma visualizaçã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 na segmentação de um item de linha ao mesmo tempo, use estes 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 funciona de maneira semelhante a qualquer outro método
list
. É possível usar o parâmetro de consulta filter
para filtrar
os resultados por TargetingType
ou
Inheritance
.
Confira um exemplo de como listar todas as opções de segmentação atribuídas a um item de linha e herdada pelo parceiro ou anunciante principal:
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 a segmentação em massa
O advertisers.lineItems.bulkEditAssignedTargetingOptions
oferece uma maneira de adicionar e remover várias opções de segmentação de vários tipos
de um ou mais itens de linha simultaneamente.
O método recebe 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.
Se a tentativa de exclusão ou criação de uma opção de segmentação atribuída causar um erro em um item de linha, a ação em massa será abandonada para esse item. A solicitação retorna uma lista de itens de linha atualizados com sucesso, além de listas de itens de linha que não foram atualizados e os erros relevantes.
Confira um exemplo de como editar em massa as opções de segmentação atribuídas a um ou mais itens de linha, considerando listas de opções de segmentação atribuídas a serem excluídas e opções de segmentação a serem criadas:
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'); }