Use the [targeting setting](https://support.google.com/google-ads/answer/7365594) in your ad groups or
campaigns to specify whether to narrow your ads to only show to specific
audience segments, or on specific content you've selected.

> [!TIP]
> **Tip:** This guide focuses on targeting and observation settings. If you want to learn how to set targeting criteria for a campaign or ad group---for example, audience targeting to specify who you want to reach---refer to the [Criteria](https://developers.google.com/google-ads/api/docs/targeting/criteria.md.txt) guide and the [Add Campaign Targeting Criteria](https://developers.google.com/google-ads/api/samples/add-campaign-targeting-criteria.md.txt) sample.

## Set up the targeting setting

You can set up details on how your various criteria types are used for targeting
by setting the [`TargetingSetting`](https://developers.google.com/google-ads/api/reference/rpc/v26/TargetingSetting.md.txt) field with an array of
[`target_restrictions`](https://developers.google.com/google-ads/api/reference/rpc/v26/TargetingSetting.md.txt#target_restrictions%5B%5D) (or by applying incremental updates
using [`target_restriction_operations`](https://developers.google.com/google-ads/api/reference/rpc/v26/TargetingSetting.md.txt#target_restriction_operations%5B%5D)). Each
[`TargetRestriction`](https://developers.google.com/google-ads/api/reference/rpc/v26/TargetRestriction.md.txt) lets you control whether a
[`TargetingDimension`](https://developers.google.com/google-ads/api/reference/rpc/v26/TargetingDimensionEnum.TargetingDimension.md.txt) (`AUDIENCE`, `TOPIC`, `GENDER`,
`AGE_RANGE`, `PLACEMENT`, `PARENTAL_STATUS`, or `INCOME_RANGE`) uses the
[`bid_only`](https://developers.google.com/google-ads/api/reference/rpc/v26/TargetRestriction.md.txt#bid_only) option or not.

> [!NOTE]
> **Note:** `TargetingDimension.KEYWORD` may be used as a custom bid dimension, but keywords are always a targeting dimension and cannot be set to `bid_only = true` (Observation) with `TargetRestriction`.

When setting `bid_only` to `true`, the targeting setting will be set to
"Observation", and the criteria won't be used to restrict traffic, but will
allow you to bid differently for different users on your lists. Setting
`bid_only` to `false` sets the targeting setting to "Targeting" and enables the
criteria to restrict ad group traffic only to users on the targeted list.

The key differences are summarized in the following table:

| Setting | `bid_only` | Effect on reach | Bidding impact |
|---|---|---|---|
| Targeting | `false` | Narrows reach to *only* the criteria selected | Can set specific bids on criteria |
| Observation | `true` | Does *not* narrow reach; ads show as normal | Allows bid *adjustments* on criteria |

### Practical scenarios

Here are short examples of *when* to use Observation mode versus Targeting mode:

Observation
:   Use Observation mode if you run a Search campaign and want to know how well a
    particular audience (for example, "sports fans") converts compared to the
    general public, without restricting your ads to only that audience. You can
    add "sports fans" as an Audience criterion with `bid_only = true`
    (Observation) and apply a +10% bid adjustment. This lets you gather
    performance data for that audience and bid more competitively for them if they
    perform well, without losing traffic from users outside that audience.

Targeting
:   Use Targeting mode if you run a Display campaign to remarket to users who
    previously visited your website but didn't convert, and you only want users on
    your "Cart Abandoners" user list to see these specific ads. In this case, you
    add the "Cart Abandoners" list as a `UserList` criterion with
    `bid_only = false` (Targeting). This ensures your ad group's budget is spent
    only on reaching this high-intent audience segment.

### Best practices

For non-demographic targeting dimensions (such as `AUDIENCE`), `bid_only` is set
to `false` by default, which means the targeting setting is set to "Targeting".
If a target restriction for one of these dimensions is omitted from or not
present in the `target_restrictions` array of a `TargetingSetting`, the system
adopts the default behavior of "Targeting" (`bid_only` is implicitly `false`)
for that dimension.

This low-level API behavior can differ from the Google Ads UI, which may
automatically apply "Observation" (`bid_only` is `true`) by default for some
targeting dimensions (such as `AUDIENCE` for Search campaigns) when campaigns or
ad groups are created. For example, Shopping campaigns created through the UI
may omit the `AUDIENCE` dimension settings by default from the API's
perspective, which means they implicitly inherit the default API behavior of
"Targeting" (`bid_only` is `false`).

If you're adding audience segments to a Search or Shopping campaign, consider
explicitly configuring the targeting setting of `bid_only` to `true` to set it
to "Observation".

If you're setting up a duplicate campaign for audience segments for search ads,
keep the targeting of `bid_only` set to `false`.

> [!IMPORTANT]
> **Important:** **Demographic dimensions always use Observation mode.** When you create an ad group and omit a [`TargetRestriction`](https://developers.google.com/google-ads/api/reference/rpc/v26/TargetRestriction.md.txt) for `AGE_RANGE`, `GENDER`, `PARENTAL_STATUS`, or `INCOME_RANGE`, the API adds one with `bid_only = true`. You can't set `bid_only = false` for demographic dimensions: doing so returns [`SettingError.TARGETING_SETTING_DEMOGRAPHIC_CRITERION_TYPE_GROUPS_MUST_BE_SET_TO_TARGET_ALL`](https://developers.google.com/google-ads/api/reference/rpc/v26/SettingErrorEnum.SettingError.md.txt#targeting_setting_demographic_criterion_type_groups_must_be_set_to_target_all) on ad group creation, or [`SettingError.TARGETING_SETTING_CANNOT_CHANGE_TARGET_ALL_TO_FALSE_FOR_DEMOGRAPHIC_CRITERION_TYPE_GROUP`](https://developers.google.com/google-ads/api/reference/rpc/v26/SettingErrorEnum.SettingError.md.txt#targeting_setting_cannot_change_target_all_to_false_for_demographic_criterion_type_group) when updating an ad group. In Observation mode, positive demographic criteria are used for reporting and bid adjustments only; your ads can still serve to all demographics. To restrict delivery, add negative [`AdGroupCriterion`](https://developers.google.com/google-ads/api/reference/rpc/v26/AdGroupCriterion.md.txt) criteria (`negative = true`) to exclude the values you don't want (including the undetermined value). At least one demographic value must remain unexcluded in each targeted dimension; attempting to exclude all values fails with [`CriterionError.CANNOT_EXCLUDE_ALL_TARGETS`](https://developers.google.com/google-ads/api/reference/rpc/v26/CriterionErrorEnum.CriterionError.md.txt#cannot_exclude_all_targets), and attempting to leave only the undetermined category unexcluded fails with [`CriterionError.CANNOT_TARGET_ONLY_UNDETERMINED`](https://developers.google.com/google-ads/api/reference/rpc/v26/CriterionErrorEnum.CriterionError.md.txt#cannot_target_only_undetermined).

### Restrictions

You cannot add or update [`targeting_setting`](https://developers.google.com/google-ads/api/reference/rpc/v26/AdGroup.md.txt#targeting_setting) on an
`AdGroup` if [`targeting_setting`](https://developers.google.com/google-ads/api/reference/rpc/v26/Campaign.md.txt#targeting_setting) is set on the
parent campaign. If the `targeting_setting` is set on the parent `Campaign`, you
must first remove the `targeting_setting` on the parent `Campaign`. Likewise,
you must first remove the `targeting_setting` on the `AdGroup` in order to set
it on the `Campaign`.

To remove a `targeting_setting` from a `Campaign` or `AdGroup`, send an `update`
operation where `targeting_setting.target_restrictions` is cleared (set to an
empty list) and include `targeting_setting.target_restrictions` in the
`update_mask`.

## Retrieve the targeting setting

To verify that your targeting is set up as you intend, check the
`targeting_setting` on ad groups or campaigns by requesting the
[`ad_group.targeting_setting.target_restrictions`](https://developers.google.com/google-ads/api/fields/v26/ad_group.md.txt#ad_group.targeting_setting.target_restrictions)
field from the [`ad_group`](https://developers.google.com/google-ads/api/fields/v26/ad_group.md.txt) resource or the
[`campaign.targeting_setting.target_restrictions`](https://developers.google.com/google-ads/api/fields/v26/campaign.md.txt#campaign.targeting_setting.target_restrictions)
field from the [`campaign`](https://developers.google.com/google-ads/api/fields/v26/campaign.md.txt) resource in a search query.

## Example

This example updates the `targeting_setting` on an ad group so that `bid_only`
is `true` for `TargetRestriction` instances with a `targeting_dimension` of
[`AUDIENCE`](https://developers.google.com/google-ads/api/reference/rpc/v26/TargetingDimensionEnum.TargetingDimension.md.txt#audience), which lets you observe performance and set
bid adjustments for users in the audience segment without restricting reach.

First, retrieve all the `ad_group.targeting_setting.target_restrictions` from
the ad group with the provided ID.


### Java

```java
String searchQuery =
    "SELECT ad_group.id, ad_group.name, ad_group.targeting_setting.target_restrictions "
        + "FROM ad_group "
        + "WHERE ad_group.id = "
        + adGroupId;
      
```

### C#

```c#
string query = $@"
    SELECT ad_group.id, ad_group.name, ad_group.targeting_setting.target_restrictions
    FROM ad_group
    WHERE ad_group.id = {adGroupId}";
      
```

### PHP

```php
$query = "SELECT ad_group.id, ad_group.name, " .
    "ad_group.targeting_setting.target_restrictions " .
    "FROM ad_group " .
    "WHERE ad_group.id = $adGroupId";
      
```

### Python

```python
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}"""
      
```

### Ruby

```ruby
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
      
```

### Perl

```perl
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";
      
```

### curl

> [!NOTE]
> **Note:** While a direct REST code sample for this step isn't provided here, you can achieve this using a manual REST request.   
>
> Refer to the Google Ads API REST interface documentation and the method-specific reference pages. You will need to construct the JSON payload based on the proto definitions.   
>
> Key Resources:
>
> - [Using REST](https://developers.google.com/google-ads/api/rest/overview.md.txt)
> - [REST Interface Structure](https://developers.google.com/google-ads/api/rest/design/overview.md.txt)
> - [JSON Field Mappings](https://developers.google.com/google-ads/api/rest/design/json-mappings.md.txt)
> - Consult the [REST API Reference](https://developers.google.com/google-ads/api/reference/rpc/latest/overview) for the specific service and method.

<br />

Next, loop through the target restrictions and reconstruct the
`TargetingSetting` objects. If the code encounters a `TargetRestriction` with a
`targeting_dimension` of `AUDIENCE` and a `bid_only` value of `false`, it
updates the `TargetRestriction` object's `bid_only` field to `true` (or
"Observation") and adds it to the `TargetingSetting` object. Otherwise, add the
`TargetRestriction` object as returned from the server to the
`TargetingSetting`.

> [!CAUTION]
> **Caution:** When updating `targeting_setting.target_restrictions` directly, you must reconstruct and pass the entire `TargetingSetting` object with all intended `target_restrictions` back to the Google Ads API. Google assumes that any `target_restrictions` missing from the `TargetingSetting` payload should be removed. Alternatively, you can use [`target_restriction_operations`](https://developers.google.com/google-ads/api/reference/rpc/v26/TargetingSetting.md.txt#target_restriction_operations%5B%5D) ([`TargetRestrictionOperation`](https://developers.google.com/google-ads/api/reference/rpc/v26/TargetRestrictionOperation.md.txt) with `Operator.ADD` or `Operator.REMOVE`) to add, replace, or remove individual `TargetRestriction` entries without passing the entire list.


### Java

```java
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));
  }
}
      
```

### C#

```c#
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
        });
    }
}
      
```

### PHP

```php
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
            ]
        );
    }
}
      
```

### Python

```python
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(
        "\tTargeting 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
      
```

### Ruby

```ruby
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
      
```

### Perl

```perl
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::V26::Common::TargetRestriction->new({
        targetingDimension => AUDIENCE,
        bidOnly            => "true"
      });
    push @{$targeting_setting->{targetRestrictions}}, $new_restriction;
  }
}
      
```

### curl

> [!NOTE]
> **Note:** While a direct REST code sample for this step isn't provided here, you can achieve this using a manual REST request.   
>
> Refer to the Google Ads API REST interface documentation and the method-specific reference pages. You will need to construct the JSON payload based on the proto definitions.   
>
> Key Resources:
>
> - [Using REST](https://developers.google.com/google-ads/api/rest/overview.md.txt)
> - [REST Interface Structure](https://developers.google.com/google-ads/api/rest/design/overview.md.txt)
> - [JSON Field Mappings](https://developers.google.com/google-ads/api/rest/design/json-mappings.md.txt)
> - Consult the [REST API Reference](https://developers.google.com/google-ads/api/reference/rpc/latest/overview) for the specific service and method.

<br />

Finally, if the code encounters a target restriction that requires updating, it
updates the ad group with the new targeting settings.


### Java

```java
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#

```c#
private void UpdateTargetingSetting(GoogleAdsClient client, long customerId, long
    adGroupId, TargetingSetting targetingSetting)
{
    // Get the AdGroupService client.
    AdGroupServiceClient adGroupServiceClient =
        client.GetService(Services.V26.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
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
    );
}
      
```

### Python

```python
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'."
    )
      
```

### Ruby

```ruby
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
      
```

### Perl

```perl
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::V26::Resources::AdGroup->new({
      resourceName =>
        Google::Ads::GoogleAds::V26::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::V26::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};
}
      
```

### curl

> [!NOTE]
> **Note:** While a direct REST code sample for this step isn't provided here, you can achieve this using a manual REST request.   
>
> Refer to the Google Ads API REST interface documentation and the method-specific reference pages. You will need to construct the JSON payload based on the proto definitions.   
>
> Key Resources:
>
> - [Using REST](https://developers.google.com/google-ads/api/rest/overview.md.txt)
> - [REST Interface Structure](https://developers.google.com/google-ads/api/rest/design/overview.md.txt)
> - [JSON Field Mappings](https://developers.google.com/google-ads/api/rest/design/json-mappings.md.txt)
> - Consult the [REST API Reference](https://developers.google.com/google-ads/api/reference/rpc/latest/overview) for the specific service and method.

<br />

The process for setting the `bid_only` field for campaigns is nearly identical.

## What's next

- Explore supported criterion types in the [Criteria guide](https://developers.google.com/google-ads/api/docs/targeting/criteria.md.txt).