Add Customer Negative Criteria
Stay organized with collections
Save and categorize content based on your preferences.
Java
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package
com.google.ads.googleads.examples.targeting
;
import
com.beust.jcommander.Parameter
;
import
com.google.ads.googleads.examples.utils.ArgumentNames
;
import
com.google.ads.googleads.examples.utils.CodeSampleParams
;
import
com.google.ads.googleads.lib.GoogleAdsClient
;
import
com.google.ads.googleads.v21.common.ContentLabelInfo
;
import
com.google.ads.googleads.v21.common.PlacementInfo
;
import
com.google.ads.googleads.v21.enums.ContentLabelTypeEnum.ContentLabelType
;
import
com.google.ads.googleads.v21.errors.GoogleAdsError
;
import
com.google.ads.googleads.v21.errors.GoogleAdsException
;
import
com.google.ads.googleads.v21.resources.CustomerNegativeCriterion
;
import
com.google.ads.googleads.v21.services.CustomerNegativeCriterionOperation
;
import
com.google.ads.googleads.v21.services.CustomerNegativeCriterionServiceClient
;
import
com.google.ads.googleads.v21.services.MutateCustomerNegativeCriteriaResponse
;
import
com.google.ads.googleads.v21.services.MutateCustomerNegativeCriteriaResult
;
import
java.io.FileNotFoundException
;
import
java.io.IOException
;
import
java.util.Arrays
;
import
java.util.List
;
/**
* Adds various types of negative criteria as exclusions at the customer level. These criteria will
* be applied to all campaigns for the customer.
*/
public
class
AddCustomerNegativeCriteria
{
private
static
class
AddCustomerNegativeCriteriaParams
extends
CodeSampleParams
{
@Parameter
(
names
=
ArgumentNames
.
CUSTOMER_ID
,
required
=
true
)
private
long
customerId
;
}
public
static
void
main
(
String
[]
args
)
{
AddCustomerNegativeCriteriaParams
params
=
new
AddCustomerNegativeCriteriaParams
();
if
(
!
params
.
parseArguments
(
args
))
{
// Either pass the required parameters for this example on the command line, or insert them
// into the code here. See the parameter class definition above for descriptions.
params
.
customerId
=
Long
.
parseLong
(
"INSERT_CUSTOMER_ID_HERE"
);
}
GoogleAdsClient
googleAdsClient
=
null
;
try
{
googleAdsClient
=
GoogleAdsClient
.
newBuilder
().
fromPropertiesFile
().
build
();
}
catch
(
FileNotFoundException
fnfe
)
{
System
.
err
.
printf
(
"Failed to load GoogleAdsClient configuration from file. Exception: %s%n"
,
fnfe
);
System
.
exit
(
1
);
}
catch
(
IOException
ioe
)
{
System
.
err
.
printf
(
"Failed to create GoogleAdsClient. Exception: %s%n"
,
ioe
);
System
.
exit
(
1
);
}
try
{
new
AddCustomerNegativeCriteria
().
runExample
(
googleAdsClient
,
params
.
customerId
);
}
catch
(
GoogleAdsException
gae
)
{
// GoogleAdsException is the base class for most exceptions thrown by an API request.
// Instances of this exception have a message and a GoogleAdsFailure that contains a
// collection of GoogleAdsErrors that indicate the underlying causes of the
// GoogleAdsException.
System
.
err
.
printf
(
"Request ID %s failed due to GoogleAdsException. Underlying errors:%n"
,
gae
.
getRequestId
());
int
i
=
0
;
for
(
GoogleAdsError
googleAdsError
:
gae
.
getGoogleAdsFailure
().
getErrorsList
())
{
System
.
err
.
printf
(
" Error %d: %s%n"
,
i
++
,
googleAdsError
);
}
System
.
exit
(
1
);
}
}
/**
* Creates customer negative criteria.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
public
static
void
runExample
(
GoogleAdsClient
googleAdsClient
,
long
customerId
)
{
try
(
CustomerNegativeCriterionServiceClient
customerNegativeCriterionServiceClient
=
googleAdsClient
.
getLatestVersion
().
createCustomerNegativeCriterionServiceClient
())
{
// Creates a negative customer criterion excluding the content label type of 'TRAGEDY'.
CustomerNegativeCriterion
tragedyCriterion
=
CustomerNegativeCriterion
.
newBuilder
()
.
setContentLabel
(
ContentLabelInfo
.
newBuilder
().
setType
(
ContentLabelType
.
TRAGEDY
).
build
())
.
build
();
// Creates a negative customer criterion excluding the placement with url
// 'http://www.example.com'.
CustomerNegativeCriterion
placementCriterion
=
CustomerNegativeCriterion
.
newBuilder
()
.
setPlacement
(
PlacementInfo
.
newBuilder
().
setUrl
(
"http://www.example.com"
).
build
())
.
build
();
// Creates the operations.
CustomerNegativeCriterionOperation
tragedyCriterionOperation
=
CustomerNegativeCriterionOperation
.
newBuilder
().
setCreate
(
tragedyCriterion
).
build
();
CustomerNegativeCriterionOperation
placementCriterionOperation
=
CustomerNegativeCriterionOperation
.
newBuilder
().
setCreate
(
placementCriterion
).
build
();
List<CustomerNegativeCriterionOperation>
operations
=
Arrays
.
asList
(
tragedyCriterionOperation
,
placementCriterionOperation
);
// Adds the negative customer criteria.
MutateCustomerNegativeCriteriaResponse
response
=
customerNegativeCriterionServiceClient
.
mutateCustomerNegativeCriteria
(
Long
.
toString
(
customerId
),
operations
);
// Displays the results.
System
.
out
.
printf
(
"Created %d new negative customer criteria.%n"
,
response
.
getResultsCount
());
for
(
MutateCustomerNegativeCriteriaResult
result
:
response
.
getResultsList
())
{
System
.
out
.
printf
(
"Created new negative customer criteria with resource name '%s'.%n"
,
result
.
getResourceName
());
}
}
}
}
C#
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using
CommandLine
;
using
Google.Ads.Gax.Examples
;
using
Google.Ads.GoogleAds.Lib
;
using
Google.Ads.GoogleAds.V21.Common
;
using
Google.Ads.GoogleAds.V21.Errors
;
using
Google.Ads.GoogleAds.V21.Resources
;
using
Google.Ads.GoogleAds.V21.Services
;
using
System
;
using
System.Collections.Generic
;
using
static
Google
.
Ads
.
GoogleAds
.
V21
.
Enums
.
ContentLabelTypeEnum
.
Types
;
namespace
Google.Ads.GoogleAds.Examples.V21
{
/// <summary>
/// This code example adds various types of negative criteria as exclusions at the customer
/// level. These criteria will be applied to all campaigns for the customer.
/// </summary>
public
class
AddCustomerNegativeCriteria
:
ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="AddCustomerNegativeCriteria"/> example.
/// </summary>
public
class
Options
:
OptionsBase
{
/// <summary>
/// The Google Ads customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID for which the call is made.")]
public
long
CustomerId
{
get
;
set
;
}
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public
static
void
Main
(
string
[]
args
)
{
Options
options
=
ExampleUtilities
.
ParseCommandLine<Options>
(
args
);
AddCustomerNegativeCriteria
codeExample
=
new
AddCustomerNegativeCriteria
();
Console
.
WriteLine
(
codeExample
.
Description
);
codeExample
.
Run
(
new
GoogleAdsClient
(),
options
.
CustomerId
);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public
override
string
Description
=
>
"This code example adds various types of negative criteria as exclusions at the "
+
"customer level. These criteria will be applied to all campaigns for the customer."
;
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
public
void
Run
(
GoogleAdsClient
client
,
long
customerId
)
{
// Get the CustomerNegativeCriterionServiceClient .
CustomerNegativeCriterionServiceClient
customerNegativeCriterionService
=
client
.
GetService
(
Services
.
V21
.
CustomerNegativeCriterionService
);
// Creates a negative customer criterion excluding the content label type of 'TRAGEDY'.
CustomerNegativeCriterion
tragedyCriterion
=
new
CustomerNegativeCriterion
()
{
ContentLabel
=
new
ContentLabelInfo
()
{
Type
=
ContentLabelType
.
Tragedy
}
};
// Creates a negative customer criterion excluding the placement with URL
// 'http://www.example.com'.
CustomerNegativeCriterion
placementCriterion
=
new
CustomerNegativeCriterion
()
{
Placement
=
new
PlacementInfo
()
{
Url
=
"http://www.example.com"
}
};
// Creates the operations.
CustomerNegativeCriterionOperation
tragedyCriterionOperation
=
new
CustomerNegativeCriterionOperation
()
{
Create
=
tragedyCriterion
};
CustomerNegativeCriterionOperation
placementCriterionOperation
=
new
CustomerNegativeCriterionOperation
()
{
Create
=
placementCriterion
};
try
{
// Adds the negative customer criteria.
MutateCustomerNegativeCriteriaResponse
response
=
customerNegativeCriterionService
.
MutateCustomerNegativeCriteria
(
customerId
.
ToString
(),
new
CustomerNegativeCriterionOperation
[]
{
tragedyCriterionOperation
,
placementCriterionOperation
});
// Displays the results.
Console
.
WriteLine
(
$"Created {response.Results.Count} new negative customer "
+
$"criteria."
);
foreach
(
MutateCustomerNegativeCriteriaResult
result
in
response
.
Results
)
{
Console
.
WriteLine
(
$"Created new negative customer criteria with resource "
+
$"name '{result.ResourceName}'."
);
}
}
catch
(
GoogleAdsException
e
)
{
Console
.
WriteLine
(
"Failure:"
);
Console
.
WriteLine
(
$"Message: {e.Message}"
);
Console
.
WriteLine
(
$"Failure: {e.Failure}"
);
Console
.
WriteLine
(
$"Request ID: {e.RequestId}"
);
throw
;
}
}
}
}
PHP
< ?php
/**
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Google\Ads\GoogleAds\Examples\Targeting;
require __DIR__ . '/../../vendor/autoload.php';
use GetOpt\GetOpt;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentNames;
use Google\Ads\GoogleAds\Examples\Utils\ArgumentParser;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V21\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V21\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V21\GoogleAdsException;
use Google\Ads\GoogleAds\V21\Common\PlacementInfo;
use Google\Ads\GoogleAds\V21\Enums\ContentLabelTypeEnum\ContentLabelType;
use Google\Ads\GoogleAds\V21\Common\ContentLabelInfo;
use Google\Ads\GoogleAds\V21\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V21\Resources\CustomerNegativeCriterion;
use Google\Ads\GoogleAds\V21\Services\CustomerNegativeCriterionOperation;
use Google\Ads\GoogleAds\V21\Services\MutateCustomerNegativeCriteriaRequest;
use Google\ApiCore\ApiException;
/**
* Adds various types of negative criteria as exclusions at the customer level. These
* criteria will be applied to all campaigns for the customer.
*/
class AddCustomerNegativeCriteria
{
private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
public static function main()
{
// Either pass the required parameters for this example on the command line, or insert them
// into the constants above.
$options = (new ArgumentParser())->parseCommandArguments([
ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT
]);
// Generate a refreshable OAuth2 credential for authentication.
$oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();
// Construct a Google Ads client configured from a properties file and the
// OAuth2 credentials above.
$googleAdsClient = (new GoogleAdsClientBuilder())->fromFile()
->withOAuth2Credential($oAuth2Credential)
->build();
try {
self::runExample(
$googleAdsClient,
$options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID
);
} catch (GoogleAdsException $googleAdsException) {
printf(
"Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
$googleAdsException->getRequestId(),
PHP_EOL,
PHP_EOL
);
foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
/** @var GoogleAdsError $error */
printf(
"\t%s: %s%s",
$error->getErrorCode()->getErrorCode(),
$error->getMessage(),
PHP_EOL
);
}
exit(1);
} catch (ApiException $apiException) {
printf(
"ApiException was thrown with message '%s'.%s",
$apiException->getMessage(),
PHP_EOL
);
exit(1);
}
}
/**
* Runs the example.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the client customer ID
*/
public static function runExample(
GoogleAdsClient $googleAdsClient,
int $customerId
) {
// Creates a negative customer criterion excluding the content label type of 'TRAGEDY'.
$tragedyCriterion = new CustomerNegativeCriterion([
'content_label' => new ContentLabelInfo([
'type' => ContentLabelType::TRAGEDY
])
]);
// Creates a negative customer criterion excluding the placement with url
// 'http://www.example.com'.
$placementCriterion = new CustomerNegativeCriterion([
'placement' => new PlacementInfo(['url' => 'http://www.example.com'])
]);
// Creates the operations.
$tragedyCriterionOperation = new CustomerNegativeCriterionOperation();
$tragedyCriterionOperation->setCreate($tragedyCriterion);
$placementCriterionOperation = new CustomerNegativeCriterionOperation();
$placementCriterionOperation->setCreate($placementCriterion);
// Issues a mutate request to add the negative customer criteria.
$customerNegativeCriterionServiceClient =
$googleAdsClient->getCustomerNegativeCriterionServiceClient();
$response = $customerNegativeCriterionServiceClient->mutateCustomerNegativeCriteria(
MutateCustomerNegativeCriteriaRequest::build(
$customerId,
[$tragedyCriterionOperation, $placementCriterionOperation]
)
);
printf(
"Added %d negative customer criteria:%s",
$response->getResults()->count(),
PHP_EOL
);
foreach ($response->getResults() as $addedCustomerNegativeCriterion) {
/** @var CustomerNegativeCriterion $addedCustomerNegativeCriterion */
print $addedCustomerNegativeCriterion->getResourceName() . PHP_EOL;
}
}
}
AddCustomerNegativeCriteria::main();
Python
#!/usr/bin/env python
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Adds various types of negative criteria as exclusions at the customer level.
These criteria will be applied to all campaigns for the given customer.
"""
import
argparse
import
sys
from
google.ads.googleads.client
import
GoogleAdsClient
from
google.ads.googleads.errors
import
GoogleAdsException
from
google.ads.googleads.v21.resources.types.customer_negative_criterion
import
(
CustomerNegativeCriterion
,
)
from
google.ads.googleads.v21.services.services.customer_negative_criterion_service
import
(
CustomerNegativeCriterionServiceClient
,
)
from
google.ads.googleads.v21.services.types.customer_negative_criterion_service
import
(
CustomerNegativeCriterionOperation
,
MutateCustomerNegativeCriteriaResponse
,
)
def
main
(
client
:
GoogleAdsClient
,
customer_id
:
str
)
-
> None
:
"""The main method that creates all necessary entities for the example.
Args:
client: an initialized GoogleAdsClient instance.
customer_id: a client customer ID.
"""
tragedy_criterion_op
:
CustomerNegativeCriterionOperation
=
client
.
get_type
(
"CustomerNegativeCriterionOperation"
)
tragedy_criterion
:
CustomerNegativeCriterion
=
tragedy_criterion_op
.
create
# Creates a negative customer criterion excluding the content label type
# of 'TRAGEDY'.
tragedy_criterion
.
content_label
.
type_
=
(
client
.
enums
.
ContentLabelTypeEnum
.
TRAGEDY
)
placement_criterion_op
:
CustomerNegativeCriterionOperation
=
(
client
.
get_type
(
"CustomerNegativeCriterionOperation"
)
)
placement_criterion
:
CustomerNegativeCriterion
=
(
placement_criterion_op
.
create
)
# Creates a negative customer criterion excluding the placement with URL
# 'http://www.example.com'.
placement_criterion
.
placement
.
url
=
"http://www.example.com"
customer_negative_criterion_service
:
(
CustomerNegativeCriterionServiceClient
)
=
client
.
get_service
(
"CustomerNegativeCriterionService"
)
# Issues a mutate request to add the negative customer criteria.
response
:
MutateCustomerNegativeCriteriaResponse
=
(
customer_negative_criterion_service
.
mutate_customer_negative_criteria
(
customer_id
=
customer_id
,
operations
=
[
tragedy_criterion_op
,
placement_criterion_op
],
)
)
print
(
f
"Added
{
len
(
response
.
results
)
}
negative customer criteria:"
)
for
negative_criterion
in
response
.
results
:
print
(
f
"Resource name: '
{
negative_criterion
.
resource_name
}
'"
)
if
__name__
==
"__main__"
:
parser
=
argparse
.
ArgumentParser
(
description
=
(
"Adds various types of negative criteria as exclusions at the "
"customer level. These criteria will be applied to all campaigns "
"for the given customer."
)
)
# The following argument(s) should be provided to run the example.
parser
.
add_argument
(
"-c"
,
"--customer_id"
,
type
=
str
,
required
=
True
,
help
=
"The Google Ads customer ID."
,
)
args
:
argparse
.
Namespace
=
parser
.
parse_args
()
# GoogleAdsClient will read the google-ads.yaml configuration file in the
# home directory if none is specified.
googleads_client
:
GoogleAdsClient
=
GoogleAdsClient
.
load_from_storage
(
version
=
"v21"
)
try
:
main
(
googleads_client
,
args
.
customer_id
,
)
except
GoogleAdsException
as
ex
:
print
(
f
'Request with ID "
{
ex
.
request_id
}
" failed with status '
f
'"
{
ex
.
error
.
code
()
.
name
}
" and includes the following errors:'
)
for
error
in
ex
.
failure
.
errors
:
print
(
f
'
\t
Error with message "
{
error
.
message
}
".'
)
if
error
.
location
:
for
field_path_element
in
error
.
location
.
field_path_elements
:
print
(
f
"
\t\t
On field:
{
field_path_element
.
field_name
}
"
)
sys
.
exit
(
1
)
Ruby
#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2017, Google Inc. All Rights Reserved.
#
# License:: Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example adds various types of negative criteria to a customer. These
# criteria will be applied to all campaigns for the customer.
require
'optparse'
require
'google/ads/google_ads'
def
add_customer_negative_criteria
(
customer_id
)
# GoogleAdsClient will read a config file from
# ENV['HOME']/google_ads_config.rb when called without parameters
client
=
Google
::
Ads
::
GoogleAds
::
GoogleAdsClient
.
new
tragedy_operation
=
client
.
operation
.
create_resource
.
customer_negative_criterion
do
|
tragedy_criterion
|
tragedy_criterion
.
content_label
=
client
.
resource
.
content_label_info
do
|
cl
|
cl
.
type
=
:TRAGEDY
end
end
placement_operation
=
client
.
operation
.
create_resource
.
customer_negative_criterion
do
|
placement_criterion
|
placement_criterion
.
placement
=
client
.
resource
.
placement_info
do
|
pl
|
pl
.
url
=
"http://example.com"
end
end
ops
=
[
tragedy_operation
,
placement_operation
]
customer_negative_criterion_service
=
client
.
service
.
customer_negative_criterion
response
=
customer_negative_criterion_service
.
mutate_customer_negative_criteria
(
customer_id
:
customer_id
,
operations
:
ops
,
)
# Display the results.
response
.
results
.
each
do
|
negative_criterion
|
puts
"Customer negative criterion with criterion resource name
#{
negative_criterion
.
resource_name
}
was added"
end
end
if
__FILE__
==
$0
options
=
{}
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
options
[
:customer_id
]
=
'INSERT_CUSTOMER_ID_HERE'
OptionParser
.
new
do
|
opts
|
opts
.
banner
=
sprintf
(
'Usage: add_customer_negative_criteria.rb [options]'
)
opts
.
separator
''
opts
.
separator
'Options:'
opts
.
on
(
'-C'
,
'--customer-id CUSTOMER-ID'
,
String
,
'Customer ID'
)
do
|
v
|
options
[
:customer_id
]
=
v
end
opts
.
separator
''
opts
.
separator
'Help:'
opts
.
on_tail
(
'-h'
,
'--help'
,
'Show this message'
)
do
puts
opts
exit
end
end
.
parse!
begin
add_customer_negative_criteria
(
options
.
fetch
(
:customer_id
)
.
tr
(
"-"
,
""
),
)
rescue
Google
::
Ads
::
GoogleAds
::
Errors
::
GoogleAdsError
=
>
e
e
.
failure
.
errors
.
each
do
|
error
|
STDERR
.
printf
(
"Error with message: %s
\n
"
,
error
.
message
)
if
error
.
location
error
.
location
.
field_path_elements
.
each
do
|
field_path_element
|
STDERR
.
printf
(
"
\t
On field: %s
\n
"
,
field_path_element
.
field_name
)
end
end
error
.
error_code
.
to_h
.
each
do
|
k
,
v
|
next
if
v
==
:UNSPECIFIED
STDERR
.
printf
(
"
\t
Type: %s
\n\t
Code: %s
\n
"
,
k
,
v
)
end
end
raise
end
end
Perl
#!/usr/bin/perl -w
#
# Copyright 2019, Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# This example adds various types of negative criteria to a customer. These
# criteria will be applied to all campaigns for the customer.
use
strict
;
use
warnings
;
use
utf8
;
use
FindBin
qw($Bin)
;
use
lib
"$Bin/../../lib"
;
use
Google::Ads::GoogleAds::Client
;
use
Google::Ads::GoogleAds::Utils::GoogleAdsHelper
;
use
Google::Ads::GoogleAds::V21::Resources::CustomerNegativeCriterion
;
use
Google::Ads::GoogleAds::V21::Common::ContentLabelInfo
;
use
Google::Ads::GoogleAds::V21::Common::PlacementInfo
;
use
Google::Ads::GoogleAds::V21::Enums::ContentLabelTypeEnum
qw(TRAGEDY)
;
use
Getopt::Long
qw(:config auto_help)
;
use
Pod::Usage
;
use
Cwd
qw(abs_path)
;
# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my
$customer_id
=
"INSERT_CUSTOMER_ID_HERE"
;
sub
add_customer_negative_criteria
{
my
(
$api_client
,
$customer_id
)
=
@_
;
# Create a negative customer criterion excluding the content label type of 'TRAGEDY'.
my
$tragedy_criterion
=
Google::Ads::GoogleAds::V21::Resources::
CustomerNegativeCriterion
-
> new
({
contentLabel
=
>
Google::Ads::GoogleAds::V21::Common::
ContentLabelInfo
-
> new
({
type
=
>
TRAGEDY
})});
# Create a negative customer criterion excluding the placement with url
# 'http://www.example.com'.
my
$placement_criterion
=
Google::Ads::GoogleAds::V21::Resources::
CustomerNegativeCriterion
-
> new
({
placement
=
>
Google::Ads::GoogleAds::V21::Common::
PlacementInfo
-
> new
({
url
=
>
"http://example.com"
})});
# Create the operations.
my
$operations
=
[{
create
=
>
$tragedy_criterion
},
{
create
=
>
$placement_criterion
}];
# Add the negative customer criteria.
my
$customer_negative_criteria_response
=
$api_client
-
> CustomerNegativeCriterionService
()
-
> mutate
({
customerId
=
>
$customer_id
,
operations
=
>
$operations
});
my
$customer_negative_criterion_results
=
$customer_negative_criteria_response
-
> {
results
};
printf
"Created %d new negative customer criteria.\n"
,
scalar
@$customer_negative_criterion_results
;
foreach
my
$result
(
@
{
$customer_negative_criterion_results
})
{
printf
"Created new negative customer criteria with resource name '%s'.\n"
,
$result
-
> {
resourceName
};
}
return
1
;
}
# Don't run the example if the file is being included.
if
(
abs_path
(
$0
)
ne
abs_path
(
__FILE__
))
{
return
1
;
}
# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my
$api_client
=
Google::Ads::GoogleAds::
Client
-
> new
();
# By default examples are set to die on any server returned fault.
$api_client
-
> set_die_on_faults
(
1
);
# Parameters passed on the command line will override any parameters set in code.
GetOptions
(
"customer_id=s"
=
>
\
$customer_id
);
# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage
(
2
)
if
not
check_params
(
$customer_id
);
# Call the example.
add_customer_negative_criteria
(
$api_client
,
$customer_id
=~
s/-//g
r
);
=pod
=head1 NAME
add_customer_negative_criteria
=head1 DESCRIPTION
This example adds various types of negative criteria to a customer. These criteria will
be applied to all campaigns for the customer.
=head1 SYNOPSIS
add_customer_negative_criteria.pl [options]
-help Show the help message.
-customer_id The Google Ads customer ID.
=cut
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License
, and code samples are licensed under the Apache 2.0 License
. For details, see the Google Developers Site Policies
. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-09-03 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Missing the information I need","missingTheInformationINeed","thumb-down"],["Too complicated / too many steps","tooComplicatedTooManySteps","thumb-down"],["Out of date","outOfDate","thumb-down"],["Samples / code issue","samplesCodeIssue","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-09-03 UTC."],[[["\u003cp\u003eThe code examples demonstrate how to add negative criteria at the customer level in Google Ads, applying exclusions across all campaigns for a given customer ID, specifically for content labels and website placements.\u003c/p\u003e\n"],["\u003cp\u003eThe Google Ads API is used to create \u003ccode\u003eCustomerNegativeCriterion\u003c/code\u003e objects, prepare \u003ccode\u003eCustomerNegativeCriterionOperation\u003c/code\u003e objects, and submit a \u003ccode\u003eMutateCustomerNegativeCriteria\u003c/code\u003e request, with each example showcasing how to interact with these core functionalities.\u003c/p\u003e\n"],["\u003cp\u003eError handling is a significant focus, with each language implementation demonstrating how to catch and handle \u003ccode\u003eGoogleAdsException\u003c/code\u003e and \u003ccode\u003eApiException\u003c/code\u003e to ensure robustness.\u003c/p\u003e\n"],["\u003cp\u003eThe examples utilize similar code structure across Java, C#, PHP, Python, Ruby and Perl, highlighting common steps like setting up authentication, creating negative criteria, preparing operations, submitting API requests, and handling responses.\u003c/p\u003e\n"],["\u003cp\u003eEach language code includes the use of specific libraries to facilitate the Google Ads Client functionalities, as well as parameter management.\u003c/p\u003e\n"]]],[],null,[]]