Update Audience Target Restriction
Stay organized with collections
Save and categorize content based on your preferences.
Java
// 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.
package
com.google.ads.googleads.examples.remarketing
;
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.lib.utils.FieldMasks
;
import
com.google.ads.googleads.v21.common.TargetRestriction
;
import
com.google.ads.googleads.v21.common.TargetingSetting
;
import
com.google.ads.googleads.v21.enums.TargetingDimensionEnum.TargetingDimension
;
import
com.google.ads.googleads.v21.errors.GoogleAdsError
;
import
com.google.ads.googleads.v21.errors.GoogleAdsException
;
import
com.google.ads.googleads.v21.resources.AdGroup
;
import
com.google.ads.googleads.v21.services.AdGroupOperation
;
import
com.google.ads.googleads.v21.services.AdGroupServiceClient
;
import
com.google.ads.googleads.v21.services.GoogleAdsRow
;
import
com.google.ads.googleads.v21.services.GoogleAdsServiceClient
;
import
com.google.ads.googleads.v21.services.GoogleAdsServiceClient.SearchPagedResponse
;
import
com.google.ads.googleads.v21.services.MutateAdGroupsResponse
;
import
com.google.ads.googleads.v21.services.SearchGoogleAdsRequest
;
import
com.google.ads.googleads.v21.utils.ResourceNames
;
import
com.google.common.collect.ImmutableList
;
import
java.io.FileNotFoundException
;
import
java.io.IOException
;
import
java.util.List
;
/** Updates the AUDIENCE target restriction of a given ad group to bid only. */
public
class
UpdateAudienceTargetRestriction
{
private
static
class
UpdateAudienceTargetRestrictionParams
extends
CodeSampleParams
{
@Parameter
(
names
=
ArgumentNames
.
CUSTOMER_ID
,
required
=
true
)
private
Long
customerId
;
@Parameter
(
names
=
ArgumentNames
.
AD_GROUP_ID
,
required
=
true
)
private
Long
adGroupId
;
}
public
static
void
main
(
String
[]
args
)
{
UpdateAudienceTargetRestrictionParams
params
=
new
UpdateAudienceTargetRestrictionParams
();
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"
);
params
.
adGroupId
=
Long
.
parseLong
(
"INSERT_AD_GROUP_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
UpdateAudienceTargetRestriction
()
.
runExample
(
googleAdsClient
,
params
.
customerId
,
params
.
adGroupId
);
}
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
);
}
}
/**
* Runs the example.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param adGroupId the ID of the ad group to update.
* @throws GoogleAdsException if an API request failed with one or more service errors.
*/
private
void
runExample
(
GoogleAdsClient
googleAdsClient
,
long
customerId
,
long
adGroupId
)
{
// Creates an empty TargetingSetting object.
TargetingSetting
.
Builder
targetingSettingBuilder
=
TargetingSetting
.
newBuilder
();
// Creates the Google Ads service client.
try
(
GoogleAdsServiceClient
googleAdsServiceClient
=
googleAdsClient
.
getLatestVersion
().
createGoogleAdsServiceClient
())
{
// Creates a search request that retrieves the targeting settings from a given ad group.
String
searchQuery
=
"SELECT ad_group.id, ad_group.name, ad_group.targeting_setting.target_restrictions "
+
"FROM ad_group "
+
"WHERE ad_group.id = "
+
adGroupId
;
// Creates a request that will retrieve all ad groups.
SearchGoogleAdsRequest
request
=
SearchGoogleAdsRequest
.
newBuilder
()
.
setCustomerId
(
Long
.
toString
(
customerId
))
.
setQuery
(
searchQuery
)
.
build
();
// Issues the search request.
SearchPagedResponse
searchPagedResponse
=
googleAdsServiceClient
.
search
(
request
);
// Iterates over all rows in all pages and prints the requested field values for the ad group
// in each row.
// Creates a flag that specifies whether or not we should update the targeting setting. We
// should only do this if we find an AUDIENCE target restriction with bid_only set to false.
boolean
shouldUpdateTargetingSetting
=
false
;
for
(
GoogleAdsRow
googleAdsRow
:
searchPagedResponse
.
iterateAll
())
{
AdGroup
adGroup
=
googleAdsRow
.
getAdGroup
();
// Prints the results.
System
.
out
.
printf
(
"Ad group with ID %d and name '%s' was found with the following targeting"
+
" restrictions.%n"
,
adGroup
.
getId
(),
adGroup
.
getName
());
List<TargetRestriction>
targetRestrictions
=
adGroup
.
getTargetingSetting
().
getTargetRestrictionsList
();
// Loops through and prints each of the target restrictions.
// Reconstructs the TargetingSetting object with the updated audience target restriction
// because Google will overwrite the entire targeting_setting field of the ad group when
// the field mask includes targeting_setting in an update operation.
for
(
TargetRestriction
targetRestriction
:
targetRestrictions
)
{
TargetingDimension
targetingDimension
=
targetRestriction
.
getTargetingDimension
();
boolean
bidOnly
=
targetRestriction
.
getBidOnly
();
System
.
out
.
printf
(
"- Targeting restriction with targeting dimension '%s' and bid only set to '%b'.%n"
,
targetingDimension
,
bidOnly
);
// Adds the target restriction to the TargetingSetting object as is if the targeting
// dimension has a value other than AUDIENCE because those should not change.
if
(
!
targetingDimension
.
equals
(
TargetingDimension
.
AUDIENCE
))
{
targetingSettingBuilder
.
addTargetRestrictions
(
targetRestriction
);
}
else
if
(
!
bidOnly
)
{
shouldUpdateTargetingSetting
=
true
;
// Adds an AUDIENCE target restriction with bid_only set to true to the targeting
// setting object. This has the effect of setting the AUDIENCE target restriction to
// "Observation". For more details about the targeting setting, visit
// https://support.google.com/google-ads/answer/7365594.
targetingSettingBuilder
.
addTargetRestrictions
(
TargetRestriction
.
newBuilder
()
.
setTargetingDimensionValue
(
TargetingDimension
.
AUDIENCE_VALUE
)
.
setBidOnly
(
true
));
}
}
}
// Only updates the TargetingSetting on the ad group if there is an AUDIENCE TargetRestriction
// with bid_only set to false.
if
(
shouldUpdateTargetingSetting
)
{
updateTargetingSetting
(
googleAdsClient
,
customerId
,
adGroupId
,
targetingSettingBuilder
.
build
());
}
else
{
System
.
out
.
println
(
"No target restrictions to update."
);
}
}
}
/**
* Updates the TargetingSetting of an ad group.
*
* @param googleAdsClient the Google Ads API client.
* @param customerId the client customer ID.
* @param adGroupId the ID of the ad group to update.
* @param targetingSetting the updated targeting setting.
*/
private
void
updateTargetingSetting
(
GoogleAdsClient
googleAdsClient
,
long
customerId
,
long
adGroupId
,
TargetingSetting
targetingSetting
)
{
// Creates the ad group service client.
try
(
AdGroupServiceClient
adGroupServiceClient
=
googleAdsClient
.
getLatestVersion
().
createAdGroupServiceClient
())
{
// Creates an ad group object with the proper resource name and updated targeting setting.
AdGroup
adGroup
=
AdGroup
.
newBuilder
()
.
setResourceName
(
ResourceNames
.
adGroup
(
customerId
,
adGroupId
))
.
setTargetingSetting
(
targetingSetting
)
.
build
();
// Constructs an operation that will update the ad group, using the FieldMasks utility to
// derive the update mask. This mask tells the Google Ads API which attributes of the
// ad group you want to change.
AdGroupOperation
operation
=
AdGroupOperation
.
newBuilder
()
.
setUpdate
(
adGroup
)
.
setUpdateMask
(
FieldMasks
.
allSetFieldsOf
(
adGroup
))
.
build
();
// Sends the operation in a mutate request.
MutateAdGroupsResponse
response
=
adGroupServiceClient
.
mutateAdGroups
(
Long
.
toString
(
customerId
),
ImmutableList
.
of
(
operation
));
// Prints the resource name of the updated object.
System
.
out
.
printf
(
"Updated targeting setting of ad group with resource name '%s'; set the AUDIENCE "
+
"target restriction to 'Observation'.%n"
,
response
.
getResults
(
0
).
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.Gax.Util
;
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
Google.Api.Gax
;
using
Google.Protobuf.Collections
;
using
System
;
using
System.Linq
;
using
static
Google
.
Ads
.
GoogleAds
.
V21
.
Enums
.
TargetingDimensionEnum
.
Types
;
namespace
Google.Ads.GoogleAds.Examples.V21
{
/// <summary>
/// This code example updates the AUDIENCE target restriction of a given ad group to bid only.
/// </summary>
public
class
UpdateAudienceTargetRestriction
:
ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="UpdateAudienceTargetRestriction"/>
/// example.
/// </summary>
public
class
Options
:
OptionsBase
{
/// <summary>
/// The Google Ads customer ID for the conversion action is added.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The Google Ads customer ID for the conversion action is added.")]
public
long
CustomerId
{
get
;
set
;
}
/// <summary>
/// The ad group ID for which to update the audience targeting restriction.
/// </summary>
[Option("adGroupId", Required = true, HelpText =
"The ad group ID for which to update the audience targeting restriction.")]
public
long
AdGroupId
{
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
);
UpdateAudienceTargetRestriction
codeExample
=
new
UpdateAudienceTargetRestriction
();
Console
.
WriteLine
(
codeExample
.
Description
);
codeExample
.
Run
(
new
GoogleAdsClient
(),
options
.
CustomerId
,
options
.
AdGroupId
);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public
override
string
Description
=
>
"This code example updates the AUDIENCE target restriction of a given ad group to "
+
"bid only."
;
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID for the conversion action is
/// added.</param>
/// <param name="adGroupId">The ad group ID for which to update the audience targeting
/// restriction.</param>
public
void
Run
(
GoogleAdsClient
client
,
long
customerId
,
long
adGroupId
)
{
// Get the GoogleAdsService client.
GoogleAdsServiceClient
googleAdsServiceClient
=
client
.
GetService
(
Services
.
V21
.
GoogleAdsService
);
// Create a search request that retrieves the targeting settings from a given ad group.
string
query
=
$
@"
SELECT ad_group.id, ad_group.name, ad_group.targeting_setting.target_restrictions
FROM ad_group
WHERE ad_group.id = {adGroupId}"
;
try
{
// Issue the search request.
PagedEnumerable<SearchGoogleAdsResponse
,
GoogleAdsRow
>
searchResponse
=
googleAdsServiceClient
.
Search
(
customerId
.
ToString
(),
query
);
// Create an empty TargetingSetting instance.
TargetingSetting
targetingSetting
=
new
TargetingSetting
();
// Create a flag that specifies whether or not we should update the targeting
// setting. We should only do this if we find an AUDIENCE target restriction with
// bid_only set to false.
bool
shouldUpdateTargetingSetting
=
false
;
// Iterate over all rows in all pages and prints the requested field values for the
// ad group in each row.
foreach
(
GoogleAdsRow
googleAdsRow
in
searchResponse
)
{
AdGroup
adGroup
=
googleAdsRow
.
AdGroup
;
Console
.
WriteLine
(
$"Ad group with ID {adGroup.Id} and name '{adGroup.Name}' "
+
"was found with the following targeting restrictions:"
);
RepeatedField<TargetRestriction>
targetRestrictions
=
adGroup
.
TargetingSetting
.
TargetRestrictions
;
// Loop through and print each of the target restrictions. Reconstruct the
// TargetingSetting object with the updated audience target restriction because
// Google will overwrite the entire targeting_setting field of the ad group when
// the field mask includes targeting_setting in an update operation.
foreach
(
TargetRestriction
targetRestriction
in
targetRestrictions
)
{
TargetingDimension
targetingDimension
=
targetRestriction
.
TargetingDimension
;
bool
bidOnly
=
targetRestriction
.
BidOnly
;
Console
.
WriteLine
(
"\tTargeting restriction with targeting dimension "
+
$"'{targetingDimension}' and bid only set to '{bidOnly}'."
);
// Add the target restriction to the TargetingSetting object as is if the
// targeting dimension has a value other than AUDIENCE because those should
// not change.
if
(
targetingDimension
!=
TargetingDimension
.
Audience
)
{
targetingSetting
.
TargetRestrictions
.
Add
(
targetRestriction
);
}
else
if
(
!
bidOnly
)
{
shouldUpdateTargetingSetting
=
true
;
// Add an AUDIENCE target restriction with bid_only set to true to the
// targeting setting object. This has the effect of setting the AUDIENCE
// target restriction to "Observation". For more details about the
// targeting setting, visit
// https://support.google.com/google-ads/answer/7365594.
targetingSetting
.
TargetRestrictions
.
Add
(
new
TargetRestriction
{
TargetingDimension
=
TargetingDimension
.
Audience
,
BidOnly
=
true
});
}
}
}
// Only update the TargetSetting on the ad group if there is an AUDIENCE
// TargetRestriction with bid_only set to false.
if
(
shouldUpdateTargetingSetting
)
{
UpdateTargetingSetting
(
client
,
customerId
,
adGroupId
,
targetingSetting
);
}
else
{
Console
.
WriteLine
(
"No target restrictions to update."
);
}
}
catch
(
GoogleAdsException
e
)
{
Console
.
WriteLine
(
"Failure:"
);
Console
.
WriteLine
(
$"Message: {e.Message}"
);
Console
.
WriteLine
(
$"Failure: {e.Failure}"
);
Console
.
WriteLine
(
$"Request ID: {e.RequestId}"
);
throw
;
}
}
/// <summary>
/// Updates the given TargetingSetting of an ad group.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The Google Ads customer ID.</param>
/// <param name="adGroupId">The ad group ID for which to update the audience targeting
/// restriction.</param>
/// <param name="targetingSetting">The updated targeting setting.</param>
private
void
UpdateTargetingSetting
(
GoogleAdsClient
client
,
long
customerId
,
long
adGroupId
,
TargetingSetting
targetingSetting
)
{
// Get the AdGroupService client.
AdGroupServiceClient
adGroupServiceClient
=
client
.
GetService
(
Services
.
V21
.
AdGroupService
);
// Create an ad group object with the updated targeting setting.
AdGroup
adGroup
=
new
AdGroup
{
ResourceName
=
ResourceNames
.
AdGroup
(
customerId
,
adGroupId
),
TargetingSetting
=
targetingSetting
};
// Construct an operation that will update the ad group, using the FieldMasks utility
// to derive the update mask. This mask tells the Google Ads API which attributes of the
// ad group you want to change.
AdGroupOperation
operation
=
new
AdGroupOperation
{
Update
=
adGroup
,
UpdateMask
=
FieldMasks
.
AllSetFieldsOf
(
adGroup
)
};
// Send the operation in a mutate request.
MutateAdGroupsResponse
response
=
adGroupServiceClient
.
MutateAdGroups
(
customerId
.
ToString
(),
new
[]
{
operation
});
// Print the resource name of the updated object.
Console
.
WriteLine
(
"Updated targeting setting of ad group with resource name "
+
$"'{response.Results.First().ResourceName}'; set the AUDIENCE target restriction "
+
"to 'Observation'."
);
}
}
}
PHP
< ?php
/**
* 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.
*/
namespace Google\Ads\GoogleAds\Examples\Remarketing;
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\V21\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V21\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V21\GoogleAdsException;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Util\FieldMasks;
use Google\Ads\GoogleAds\Util\V21\ResourceNames;
use Google\Ads\GoogleAds\V21\Common\TargetingSetting;
use Google\Ads\GoogleAds\V21\Common\TargetRestriction;
use Google\Ads\GoogleAds\V21\Enums\TargetingDimensionEnum\TargetingDimension;
use Google\Ads\GoogleAds\V21\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V21\Resources\AdGroup;
use Google\Ads\GoogleAds\V21\Services\AdGroupOperation;
use Google\Ads\GoogleAds\V21\Services\GoogleAdsRow;
use Google\Ads\GoogleAds\V21\Services\MutateAdGroupsRequest;
use Google\Ads\GoogleAds\V21\Services\SearchGoogleAdsRequest;
use Google\ApiCore\ApiException;
/**
* This example demonstrates how to update the AUDIENCE target restriction of a given ad group to
* bid only.
*/
class UpdateAudienceTargetRestriction
{
private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
private const AD_GROUP_ID = 'INSERT_AD_GROUP_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,
ArgumentNames::AD_GROUP_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,
$options[ArgumentNames::AD_GROUP_ID] ?: self::AD_GROUP_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 customer ID
* @param int $adGroupId the ID of the ad group to update
*/
public static function runExample(
GoogleAdsClient $googleAdsClient,
int $customerId,
int $adGroupId
) {
$googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
// Creates a query that retrieves the targeting settings from a given ad group.
$query = "SELECT ad_group.id, ad_group.name, " .
"ad_group.targeting_setting.target_restrictions " .
"FROM ad_group " .
"WHERE ad_group.id = $adGroupId";
// Issues a search request.
$response =
$googleAdsServiceClient->search(SearchGoogleAdsRequest::build($customerId, $query));
// Iterates over all rows in all pages and prints the requested field values for
// the ad group in each row.
// Creates a flag that specifies whether or not we should update the targeting setting. We
// should only do this if we find an AUDIENCE target restriction with bid_only set to false.
$shouldUpdateTargetingSetting = false;
$targetRestrictions = [];
foreach ($response->iterateAllElements() as $googleAdsRow) {
/** @var GoogleAdsRow $googleAdsRow */
$adGroup = $googleAdsRow->getAdGroup();
// Prints the results.
printf(
"Ad group with ID %d and name '%s' was found with the following targeting " .
"restrictions.%s",
$adGroup->getId(),
$adGroup->getName(),
PHP_EOL
);
// Loops through and prints each of the target restrictions.
// Builds the updated audience target restriction based on the current because Google
// will overwrite the entire targeting_setting field of the ad group when the field
// mask includes targeting_setting in an update operation.
foreach (
$adGroup->getTargetingSetting()->getTargetRestrictions() as $targetRestriction
) {
// Prints the results.
$targetingDimension = $targetRestriction->getTargetingDimension();
$bidOnly = $targetRestriction->getBidOnly();
printf(
"- Targeting restriction with targeting dimension '%s' and bid only set to " .
"'%s'.%s",
TargetingDimension::name($targetingDimension),
$bidOnly ? 'true' : 'false',
PHP_EOL
);
// Adds the target restriction to the TargetingSetting object as is if the targeting
// dimension has a value other than AUDIENCE because those should not change.
if ($targetingDimension !== TargetingDimension::AUDIENCE) {
$targetRestrictions[] = $targetRestriction;
} elseif (!$bidOnly) {
$shouldUpdateTargetingSetting = true;
// Adds an AUDIENCE target restriction with bid_only set to true to the
// targeting setting object. This has the effect of setting the AUDIENCE
// target restriction to "Observation".
// For more details about the targeting setting, visit
// https://support.google.com/google-ads/answer/7365594.
$targetRestrictions[] = new TargetRestriction([
'targeting_dimension' => TargetingDimension::AUDIENCE,
'bid_only' => true
]);
}
}
}
// Only updates the TargetingSetting on the ad group if there is an AUDIENCE
// TargetRestriction with bid_only set to false.
if ($shouldUpdateTargetingSetting) {
self::updateTargetingSetting(
$googleAdsClient,
$customerId,
$adGroupId,
new TargetingSetting([
'target_restrictions' => $targetRestrictions
])
);
} else {
print "No target restrictions to update." . PHP_EOL;
}
}
/**
* Updates the TargetingSetting of an ad group.
*
* @param GoogleAdsClient $googleAdsClient the Google Ads API client
* @param int $customerId the customer ID
* @param int $adGroupId the ID of the ad group to update
* @param TargetingSetting $targetingSetting the updated targeting setting
*/
private static function updateTargetingSetting(
GoogleAdsClient $googleAdsClient,
int $customerId,
int $adGroupId,
TargetingSetting $targetingSetting
) {
// Creates an ad group object with the proper resource name and updated targeting setting.
$adGroup = new AdGroup([
'resource_name' => ResourceNames::forAdGroup($customerId, $adGroupId),
'targeting_setting' => $targetingSetting
]);
// Constructs an operation that will update the ad group with the specified resource name,
// using the FieldMasks utility to derive the update mask. This mask tells the Google Ads
// API which attributes of the ad group you want to change.
$adGroupOperation = new AdGroupOperation();
$adGroupOperation->setUpdate($adGroup);
$adGroupOperation->setUpdateMask(FieldMasks::allSetFieldsOf($adGroup));
// Issues a mutate request to update the ad group.
$adGroupServiceClient = $googleAdsClient->getAdGroupServiceClient();
$response = $adGroupServiceClient->mutateAdGroups(
MutateAdGroupsRequest::build($customerId, [$adGroupOperation])
);
// Prints the resource name of the updated ad group.
printf(
"Updated targeting setting of ad group with resource name '%s'; set the AUDIENCE " .
"target restriction to 'Observation'.%s",
$response->getResults()[0]->getResourceName(),
PHP_EOL
);
}
}
UpdateAudienceTargetRestriction::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.
"""Updates the audience target restriction of a given ad group to bid only."""
import
argparse
import
sys
from
google.ads.googleads.client
import
GoogleAdsClient
from
google.ads.googleads.errors
import
GoogleAdsException
from
google.ads.googleads.v21.common.types.targeting_setting
import
(
TargetingSetting
,
TargetRestriction
,
)
from
google.ads.googleads.v21.enums.types.targeting_dimension
import
(
TargetingDimensionEnum
,
)
from
google.ads.googleads.v21.resources.types.ad_group
import
AdGroup
from
google.ads.googleads.v21.services.services.ad_group_service
import
(
AdGroupServiceClient
,
)
from
google.ads.googleads.v21.services.types.ad_group_service
import
(
AdGroupOperation
,
MutateAdGroupsResponse
,
)
from
google.ads.googleads.v21.services.services.google_ads_service
import
(
GoogleAdsServiceClient
,
)
from
google.ads.googleads.v21.services.types.google_ads_service
import
(
SearchGoogleAdsResponse
,
)
from
google.api_core
import
protobuf_helpers
def
main
(
client
:
GoogleAdsClient
,
customer_id
:
str
,
ad_group_id
:
str
)
-
> None
:
"""Updates the audience target restriction of a given ad group to bid only.
Args:
client: An initialized GoogleAdsClient instance.
customer_id: The client customer ID string.
ad_group_id: The ad group ID for which to update the audience targeting
restriction.
"""
# Get the GoogleAdsService client.
googleads_service
:
GoogleAdsServiceClient
=
client
.
get_service
(
"GoogleAdsService"
)
# Create a search request that retrieves the targeting settings from a given
# ad group.
query
:
str
=
f
"""
SELECT
ad_group.id,
ad_group.name,
ad_group.targeting_setting.target_restrictions
FROM ad_group
WHERE ad_group.id =
{
ad_group_id
}
"""
# Issue the search request.
search_response
:
SearchGoogleAdsResponse
=
googleads_service
.
search
(
customer_id
=
customer_id
,
query
=
query
)
targeting_dimension_enum
:
TargetingDimensionEnum
=
(
client
.
enums
.
TargetingDimensionEnum
)
# Create an empty TargetingSetting instance.
targeting_setting
:
TargetingSetting
=
client
.
get_type
(
"TargetingSetting"
)
# Create a flag that specifies whether or not we should update the
# targeting setting. We should only do this if we find an audience
# target restriction with bid_only set to false.
should_update_targeting_setting
:
bool
=
False
ad_group
:
AdGroup
=
next
(
iter
(
search_response
))
.
ad_group
print
(
f
"Ad group with ID
{
ad_group
.
id
}
and name '
{
ad_group
.
name
}
' "
"was found with the following targeting restrictions:"
)
target_restrictions
:
"list[TargetRestriction]"
=
(
ad_group
.
targeting_setting
.
target_restrictions
)
# Loop through and print each of the target restrictions.
# Reconstruct the TargetingSetting object with the updated audience
# target restriction because Google Ads will overwrite the entire
# targeting_setting field of the ad group when the field mask
# includes targeting_setting in an update operation.
target_restriction
:
TargetRestriction
for
target_restriction
in
target_restrictions
:
targeting_dimension
:
TargetingDimensionEnum
.
TargetingDimension
=
(
target_restriction
.
targeting_dimension
)
bid_only
:
bool
=
target_restriction
.
bid_only
print
(
"
\t
Targeting restriction with targeting dimension "
f
"'
{
targeting_dimension
.
name
}
' "
f
"and bid only set to '
{
bid_only
}
'."
)
# Add the target restriction to the TargetingSetting object as
# is if the targeting dimension has a value other than audience
# because those should not change.
if
targeting_dimension
!=
targeting_dimension_enum
.
AUDIENCE
:
targeting_setting
.
target_restrictions
.
append
(
target_restriction
)
elif
not
bid_only
:
should_update_targeting_setting
:
bool
=
True
# Add an audience target restriction with bid_only set to
# true to the targeting setting object. This has the effect
# of setting the audience target restriction to
# "Observation". For more details about the targeting
# setting, visit
# https://support.google.com/google-ads/answer/7365594.
new_target_restriction
:
TargetRestriction
=
(
targeting_setting
.
target_restrictions
.
add
()
)
new_target_restriction
.
targeting_dimension
=
(
targeting_dimension_enum
.
AUDIENCE
)
new_target_restriction
.
bid_only
=
True
# Only update the TargetSetting on the ad group if there is an audience
# TargetRestriction with bid_only set to false.
if
should_update_targeting_setting
:
update_targeting_setting
(
client
,
customer_id
,
ad_group_id
,
targeting_setting
)
else
:
print
(
"No target restrictions to update."
)
def
update_targeting_setting
(
client
:
GoogleAdsClient
,
customer_id
:
str
,
ad_group_id
:
str
,
targeting_setting
:
TargetingSetting
,
)
-
> None
:
"""Updates the given TargetingSetting of an ad group.
Args:
client: The Google Ads client.
customer_id: The Google Ads customer ID.
ad_group_id: The ad group ID for which to update the audience targeting
restriction.
targeting_setting: The updated targeting setting.
"""
# Get the AdGroupService client.
ad_group_service
:
AdGroupServiceClient
=
client
.
get_service
(
"AdGroupService"
)
# Construct an operation that will update the ad group.
ad_group_operation
:
AdGroupOperation
=
client
.
get_type
(
"AdGroupOperation"
)
# Populate the ad group object with the updated targeting setting.
ad_group
:
AdGroup
=
ad_group_operation
.
update
ad_group
.
resource_name
=
ad_group_service
.
ad_group_path
(
customer_id
,
ad_group_id
)
ad_group
.
targeting_setting
.
target_restrictions
.
extend
(
targeting_setting
.
target_restrictions
)
# Use the field_mask utility to derive the update mask. This mask tells the
# Google Ads API which attributes of the ad group you want to change.
client
.
copy_from
(
ad_group_operation
.
update_mask
,
protobuf_helpers
.
field_mask
(
None
,
ad_group
.
_pb
),
)
# Send the operation in a mutate request and print the resource name of the
# updated object.
mutate_ad_groups_response
:
MutateAdGroupsResponse
=
(
ad_group_service
.
mutate_ad_groups
(
customer_id
=
customer_id
,
operations
=
[
ad_group_operation
]
)
)
print
(
"Updated targeting setting of ad group with resource name "
f
"'
{
mutate_ad_groups_response
.
results
[
0
]
.
resource_name
}
'; set the "
"audience target restriction to 'Observation'."
)
if
__name__
==
"__main__"
:
parser
:
argparse
.
ArgumentParser
=
argparse
.
ArgumentParser
(
description
=
"Updates the audience target restriction of a given ad "
"group to bid only."
)
# 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."
,
)
parser
.
add_argument
(
"-a"
,
"--ad_group_id"
,
type
=
str
,
required
=
True
,
help
=
"The ad group ID for which to update the audience targeting "
"restriction."
,
)
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
,
args
.
ad_group_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 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.
#
# This example demonstrates how to update the AUDIENCE target restriction of a
# given ad group to bid only.
require
'optparse'
require
'google/ads/google_ads'
require
'date'
def
update_audience_target_restriction
(
customer_id
,
ad_group_id
)
# GoogleAdsClient will read a config file from
# ENV['HOME']/google_ads_config.rb when called without parameters
client
=
Google
::
Ads
::
GoogleAds
::
GoogleAdsClient
.
new
# Creates a query that retrieves the targeting settings from a given ad group.
query
=
<< ~
QUERY
SELECT
ad_group
.
id
,
ad_group
.
name
,
ad_group
.
targeting_setting
.
target_restrictions
FROM
ad_group
WHERE
ad_group
.
id
=
#{ad_group_id}
QUERY
# Issues a search request.
response
=
client
.
service
.
google_ads
.
search
(
customer_id
:
customer_id
,
query
:
query
,
)
# Iterates over all rows in all pages and prints the requested field values
# for the ad group in each row.
# Creates a flag that specifies whether or not we should update the targeting
# setting. We should only do this if we find an AUDIENCE target restriction
# with bid_only set to false.
should_update_targeting_setting
=
false
target_restrictions
=
[]
response
.
each
do
|
row
|
ad_group
=
row
.
ad_group
# Prints the results.
puts
"Ad group with ID
#{
ad_group
.
id
}
and name
#{
ad_group
.
name
}
was found "
\
"with the following targeting restrictions:"
# Loops through and prints each of the target restrictions.
# Builds the updated audience target restriction based on the current
# because Google will overwrite the entire targeting_setting field of the
# ad group when the field mask includes targeting_setting in an update
# operation.
ad_group
.
targeting_setting
.
target_restrictions
.
each
do
|
r
|
# Prints the results.
targeting_dimension
=
r
.
targeting_dimension
bid_only
=
r
.
bid_only
puts
"- Targeting restriction with targeting dimension "
\
"
#{
targeting_dimension
}
and bid only set to
#{
bid_only
}
."
# Adds the target restriction to the TargetingSetting object as is if the
# targeting dimension has a value other than AUDIENCE because those should
# not change.
if
targeting_dimension
!=
:AUDIENCE
target_restrictions
<<
r
elsif
!
bid_only
should_update_targeting_setting
=
true
# Adds an AUDIENCE target restriction with bid_only set to true to the
# targeting setting object. This has the effect of setting the AUDIENCE
# target restriction to "Observation".
# For more details about the targeting setting, visit
# https://support.google.com/google-ads/answer/7365594.
target_restrictions
<<
client
.
resource
.
target_restriction
do
|
tr
|
tr
.
targeting_dimension
=
:AUDIENCE
tr
.
bid_only
=
true
end
end
end
end
# Only updates the TargetingSetting on the ad group if there is an AUDIENCE
# TargetRestriction with bid_only set to false.
if
should_update_targeting_setting
new_targeting_setting
=
client
.
resource
.
targeting_setting
do
|
s
|
target_restrictions
.
each
do
|
restriction
|
s
.
target_restrictions
<<
restriction
end
end
update_targeting_setting
(
client
,
customer_id
,
ad_group_id
,
new_targeting_setting
,
)
else
puts
"No target restrictions to update."
end
end
# Updates the TargetingSetting of an ad group.
def
update_targeting_setting
(
client
,
customer_id
,
ad_group_id
,
targeting_setting
)
# Constructs an operation that will update the ad group with the specified
# resource name.
ad_group_resource_name
=
client
.
path
.
ad_group
(
customer_id
,
ad_group_id
)
operation
=
client
.
operation
.
update_resource
.
ad_group
(
ad_group_resource_name
)
do
|
ag
|
ag
.
targeting_setting
=
targeting_setting
end
# Issues a mutate request to update the ad group.
response
=
client
.
service
.
ad_group
.
mutate_ad_groups
(
customer_id
:
customer_id
,
operations
:
[
operation
]
,
)
# Prints the resource name of the updated ad group.
puts
"Updated targeting setting of ad group with resource name "
\
"
#{
response
.
results
.
first
.
resource_name
}
; set the AUDIENCE target "
\
"restriction to 'Observation'."
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'
options
[
:ad_group_id
]
=
'INSERT_AD_GROUP_ID_HERE'
OptionParser
.
new
do
|
opts
|
opts
.
banner
=
sprintf
(
'Usage: %s [options]'
,
File
.
basename
(
__FILE__
))
opts
.
separator
''
opts
.
separator
'Options:'
opts
.
on
(
'-C'
,
'--customer-id CUSTOMER-ID'
,
String
,
'Customer ID'
)
do
|
v
|
options
[
:customer_id
]
=
v
end
opts
.
on
(
'-A'
,
'--ad-group-id AD-GROUP-ID'
,
String
,
'Ad Group ID'
)
do
|
v
|
options
[
:ad_group_id
]
=
v
end
opts
.
separator
''
opts
.
separator
'Help:'
opts
.
on_tail
(
'-h'
,
'--help'
,
'Show this message'
)
do
puts
opts
exit
end
end
.
parse!
begin
update_audience_target_restriction
(
options
.
fetch
(
:customer_id
)
.
tr
(
"-"
,
""
),
options
.
fetch
(
:ad_group_id
),
)
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 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.
#
# This code example updates the AUDIENCE target restriction of a given ad group
# to bid only.
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::Utils::FieldMasks
;
use
Google::Ads::GoogleAds::Utils::SearchStreamHandler
;
use
Google::Ads::GoogleAds::V21::Resources::FeedItemAttributeValue
;
use
Google::Ads::GoogleAds::V21::Resources::AdGroup
;
use
Google::Ads::GoogleAds::V21::Common::TargetingSetting
;
use
Google::Ads::GoogleAds::V21::Common::TargetRestriction
;
use
Google::Ads::GoogleAds::V21::Enums::TargetingDimensionEnum
qw(AUDIENCE)
;
use
Google::Ads::GoogleAds::V21::Services::AdGroupService::AdGroupOperation
;
use
Google::Ads::GoogleAds::V21::Services::GoogleAdsService::SearchGoogleAdsStreamRequest
;
use
Google::Ads::GoogleAds::V21::Utils::ResourceNames
;
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"
;
my
$ad_group_id
=
"INSERT_AD_GROUP_ID_HERE"
;
sub
update_audience_target_restriction
{
my
(
$api_client
,
$customer_id
,
$ad_group_id
)
=
@_
;
# Create a flag that specifies whether or not we should update the targeting
# setting. We should only do this if we find an AUDIENCE target restriction
# with bid_only set to false.
my
$should_update_target_setting
=
0
;
# Create an empty TargetingSetting instance.
my
$targeting_setting
=
Google::Ads::GoogleAds::V21::Common::
TargetingSetting
-
> new
();
# Create a search query that retrieves the targeting settings from a given
# ad group.
my
$query
=
"SELECT ad_group.id, ad_group.name, "
.
"ad_group.targeting_setting.target_restrictions FROM ad_group "
.
"WHERE ad_group.id = $ad_group_id"
;
# Create a search Google Ads stream request.
my
$search_stream_request
=
Google::Ads::GoogleAds::V21::Services::GoogleAdsService::
SearchGoogleAdsStreamRequest
-
> new
({
customerId
=
>
$customer_id
,
query
=
>
$query
,
});
# Get the GoogleAdsService.
my
$google_ads_service
=
$api_client
-
> GoogleAdsService
();
my
$search_stream_handler
=
Google::Ads::GoogleAds::Utils::
SearchStreamHandler
-
> new
({
service
=
>
$google_ads_service
,
request
=
>
$search_stream_request
});
# Issue a search request and process the stream response.
$search_stream_handler
-
> process_contents
(
sub
{
my
$google_ads_row
=
shift
;
my
$ad_group
=
$google_ads_row
-
> {
adGroup
};
# Print the requested ad group values from each row.
printf
"Ad group with ID %d and name '%s' was found with the following "
.
"targeting restrictions:\n"
,
$ad_group
-
> {
id
},
$ad_group
-
> {
name
};
my
@target_restrictions
=
@
{
$ad_group
-
> {
targetingSetting
}{
targetRestrictions
}};
# Loop through and print each of the target restrictions. Reconstruct the
# TargetingSetting object with the updated audience target restriction
# because Google will overwrite the entire targeting_setting field of the
# ad group when the field mask includes targeting_setting in an update
# operation.
foreach
my
$target_restriction
(
@target_restrictions
)
{
my
$targeting_dimension
=
$target_restriction
-
> {
targetingDimension
};
printf
"\tTargeting restriction with targeting dimension '%s' and bid "
.
"only set to '%s'.\n"
,
$targeting_dimension
,
$target_restriction
-
> {
bidOnly
}
?
"TRUE"
:
"FALSE"
;
# Add the target restriction to the TargetingSetting object as is if the
# targeting dimension has a value other than AUDIENCE because those
# should not change.
if
(
$targeting_dimension
ne
AUDIENCE
)
{
$target_restriction
-
> {
bidOnly
}
=
$target_restriction
-
> {
bidOnly
}
?
"true"
:
"false"
;
push
@
{
$targeting_setting
-
> {
targetRestrictions
}},
$target_restriction
;
}
elsif
(
!
$target_restriction
-
> {
bidOnly
})
{
$should_update_target_setting
=
1
;
# Add an AUDIENCE target restriction with bid_only set to true to the
# targeting setting object. This has the effect of setting the
# AUDIENCE target restriction to "Observation". For more details about
# the targeting setting, visit
# https://support.google.com/google-ads/answer/7365594.
my
$new_restriction
=
Google::Ads::GoogleAds::V21::Common::
TargetRestriction
-
> new
({
targetingDimension
=
>
AUDIENCE
,
bidOnly
=
>
"true"
});
push
@
{
$targeting_setting
-
> {
targetRestrictions
}},
$new_restriction
;
}
}
});
# Only update the TargetSetting on the ad group if there is an AUDIENCE
# TargetRestriction with bid_only set to false.
if
(
$should_update_target_setting
)
{
update_targeting_setting
(
$api_client
,
$customer_id
,
$ad_group_id
,
$targeting_setting
);
}
else
{
print
"No target restrictions to update.\n"
;
}
return
1
;
}
# Updates the given TargetingSetting of an ad group.
sub
update_targeting_setting
{
my
(
$api_client
,
$customer_id
,
$ad_group_id
,
$targeting_setting
)
=
@_
;
# Construct an ad group object with the updated targeting setting.
my
$ad_group
=
Google::Ads::GoogleAds::V21::Resources::
AdGroup
-
> new
({
resourceName
=
>
Google::Ads::GoogleAds::V21::Utils::ResourceNames::
ad_group
(
$customer_id
,
$ad_group_id
),
targetingSetting
=
>
$targeting_setting
});
# Create an operation that will update the ad group, using the FieldMasks
# utility to derive the update mask. This mask tells the Google Ads API which
# attributes of the ad group you want to change.
my
$ad_group_operation
=
Google::Ads::GoogleAds::V21::Services::AdGroupService::
AdGroupOperation
-
>
new
({
update
=
>
$ad_group
,
updateMask
=
>
all_set_fields_of
(
$ad_group
)});
# Send the operation in a mutate request and print the resource name of the
# updated resource.
my
$ad_groups_response
=
$api_client
-
> AdGroupService
()
-
> mutate
({
customerId
=
>
$customer_id
,
operations
=
>
[
$ad_group_operation
]});
printf
"Updated targeting setting of ad group with resourceName "
.
"'%s'; set the AUDIENCE target restriction to 'Observation'.\n"
,
$ad_groups_response
-
> {
results
}[
0
]{
resourceName
};
}
# 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
,
"ad_group_id=i"
=
>
\
$ad_group_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
,
$ad_group_id
);
# Call the example.
update_audience_target_restriction
(
$api_client
,
$customer_id
=~
s/-//g
r
,
$ad_group_id
);
=pod
=head1 NAME
update_audience_target_restriction
=head1 DESCRIPTION
This code example updates the AUDIENCE target restriction of a given ad group
to bid only.
=head1 SYNOPSIS
update_audience_target_restriction.pl [options]
-help Show the help message.
-customer_id The Google Ads customer ID.
-ad_group_id The ad group ID for which to update the audience
targeting restriction.
=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 modifies an ad group's audience targeting to "Observation" mode, allowing the ad group to observe the audience without actively targeting it for bidding.\u003c/p\u003e\n"],["\u003cp\u003eIt achieves this by retrieving the ad group's targeting settings, locating the audience restriction, and updating the \u003ccode\u003ebid_only\u003c/code\u003e flag to \u003ccode\u003etrue\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eThe provided examples showcase this functionality in Ruby and Perl, utilizing the Google Ads API for interaction.\u003c/p\u003e\n"],["\u003cp\u003eThe code assumes an existing audience target restriction within the ad group for proper execution.\u003c/p\u003e\n"],["\u003cp\u003eBoth targeting and observation modes allow ads to be shown to the audience, but observation mode prevents bids from being adjusted based on audience criteria.\u003c/p\u003e\n"]]],[],null,[]]