Labels let you categorize your campaigns, ad groups, ads, and keywords, and use
those categories to simplify your workflow in a variety of ways.

This guide covers the steps required to do the following:

- Create labels programmatically using [`LabelService`](https://developers.google.com/google-ads/api/reference/rpc/v26/LabelService.md.txt).
- Assign labels to your campaigns using [`CampaignLabelService`](https://developers.google.com/google-ads/api/reference/rpc/v26/CampaignLabelService.md.txt) requests.
- Retrieve and filter report results by label using [`GoogleAdsService`](https://developers.google.com/google-ads/api/reference/rpc/v26/GoogleAdsService.md.txt) queries.

This guide focuses on campaigns, but you can use the same approach for ad
groups, ads, and keywords. This API also provides
[`CustomerLabelService`](https://developers.google.com/google-ads/api/reference/rpc/v26/CustomerLabelService.md.txt), which enables
manager accounts to assign labels to child accounts.

## Use cases

Typical scenarios for using
[labels](https://support.google.com/google-ads/answer/2475865) include the
following:

- Your account has campaigns you enable only during certain times of the year, and you want to include or exclude those campaigns from reports.
- You added a new set of keywords to your ad group and you want to compare their stats to other keywords in your ad group.
- Users of your Google Ads account each manage a subset of campaigns and you want a way to identify the set of campaigns for each user.
- Your app needs to mark the status of certain objects.

## Create labels

Create labels using a [`Label`](https://developers.google.com/google-ads/api/reference/rpc/v26/Label.md.txt) object with its
`text_label` field set:

1. Create a [`TextLabel`](https://developers.google.com/google-ads/api/reference/rpc/v26/TextLabel.md.txt) instance containing a background color and description.
2. Create a `Label` instance and assign the `TextLabel` to its `text_label` field.
3. Wrap the `Label` in a `LabelOperation` (`create`) and send it to [`LabelService.MutateLabels`](https://developers.google.com/google-ads/api/reference/rpc/v26/LabelService/MutateLabels.md.txt).

Take note of the created label's ID for later queries. The ID is embedded in the
`resource_name` field in the
[`MutateLabelResult`](https://developers.google.com/google-ads/api/reference/rpc/v26/MutateLabelResult.md.txt) returned in the
[`MutateLabelsResponse`](https://developers.google.com/google-ads/api/reference/rpc/v26/MutateLabelsResponse.md.txt).

You can also use a [`GoogleAdsService`](https://developers.google.com/google-ads/api/reference/rpc/v26/GoogleAdsService.md.txt) `Search`
or `SearchStream` request to retrieve label IDs and resource names.

## Assign labels

You can assign labels to your campaigns, customers, ad groups, criteria, or ads
using the `Mutate` operation in the corresponding service.

For example, to assign labels to a campaign, pass one or more
[`CampaignLabelOperation`](https://developers.google.com/google-ads/api/reference/rpc/v26/CampaignLabelOperation.md.txt) objects to
[`CampaignLabelService.MutateCampaignLabels`](https://developers.google.com/google-ads/api/reference/rpc/v26/CampaignLabelService/MutateCampaignLabels.md.txt). Each
`CampaignLabelOperation` includes a
[`CampaignLabel`](https://developers.google.com/google-ads/api/reference/rpc/v26/CampaignLabel.md.txt) instance, which requires full
resource names in these fields:

- `label`: Resource name of a label (for example, `customers/{customer_id}/labels/{label_id}`).
- `campaign`: Resource name of a campaign (for example, `customers/{customer_id}/campaigns/{campaign_id}`).

Create a `CampaignLabel` instance for each label-campaign pair. Wrap it in a
`CampaignLabelOperation` with the `create` operation and send it to
`CampaignLabelService.MutateCampaignLabels`.

### Add campaign labels

Here's a code example showing how to add a campaign label to a list of
campaigns:


### Java

```java
private void runExample(
    GoogleAdsClient googleAdsClient, long customerId, List<Long> campaignIds, Long labelId) {
  // Gets the resource name of the label to be added across all given campaigns.
  String labelResourceName = ResourceNames.label(customerId, labelId);

  List<CampaignLabelOperation> operations = new ArrayList<>(campaignIds.size());
  // Creates a campaign label operation for each campaign.
  for (Long campaignId : campaignIds) {
    // Gets the resource name of the given campaign.
    String campaignResourceName = ResourceNames.campaign(customerId, campaignId);
    // Creates the campaign label.
    CampaignLabel campaignLabel =
        CampaignLabel.newBuilder()
            .setCampaign(campaignResourceName)
            .setLabel(labelResourceName)
            .build();

    operations.add(CampaignLabelOperation.newBuilder().setCreate(campaignLabel).build());
  }

  try (CampaignLabelServiceClient campaignLabelServiceClient =
      googleAdsClient.getLatestVersion().createCampaignLabelServiceClient()) {
    MutateCampaignLabelsResponse response =
        campaignLabelServiceClient.mutateCampaignLabels(Long.toString(customerId), operations);
    System.out.printf("Added %d campaign labels:%n", response.getResultsCount());
    for (MutateCampaignLabelResult result : response.getResultsList()) {
      System.out.println(result.getResourceName());
    }
  }
}
      
```

### C#

```c#
public void Run(GoogleAdsClient client, long customerId, long[] campaignIds, long labelId)
{
    // Get the CampaignLabelServiceClient.
    CampaignLabelServiceClient campaignLabelService =
        client.GetService(Services.V26.CampaignLabelService);

    // Gets the resource name of the label to be added across all given campaigns.
    string labelResourceName = ResourceNames.Label(customerId, labelId);

    List<CampaignLabelOperation> operations = new List<CampaignLabelOperation>();
    // Creates a campaign label operation for each campaign.
    foreach (long campaignId in campaignIds)
    {
        // Gets the resource name of the given campaign.
        string campaignResourceName = ResourceNames.Campaign(customerId, campaignId);
        // Creates the campaign label.
        CampaignLabel campaignLabel = new CampaignLabel()
        {
            Campaign = campaignResourceName,
            Label = labelResourceName
        };

        operations.Add(new CampaignLabelOperation()
        {
            Create = campaignLabel
        });
    }

    // Send the operation in a mutate request.
    try
    {
        MutateCampaignLabelsResponse response =
            campaignLabelService.MutateCampaignLabels(customerId.ToString(), operations);
        Console.WriteLine($"Added {response.Results} campaign labels:");

        foreach (MutateCampaignLabelResult result in response.Results)
        {
            Console.WriteLine(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
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        array $campaignIds,
        int $labelId
    ) {
        // Gets the resource name of the label to be added across all given campaigns.
        $labelResourceName = ResourceNames::forLabel($customerId, $labelId);

        // Creates a campaign label operation for each campaign.
        $operations = [];
        foreach ($campaignIds as $campaignId) {
            // Creates the campaign label.
            $campaignLabel = new CampaignLabel(
                [
                'campaign' => ResourceNames::forCampaign($customerId, $campaignId),
                'label' => $labelResourceName
                ]
            );
            $campaignLabelOperation = new CampaignLabelOperation();
            $campaignLabelOperation->setCreate($campaignLabel);
            $operations[] = $campaignLabelOperation;
        }

        // Issues a mutate request to add the labels to the campaigns.
        $campaignLabelServiceClient = $googleAdsClient->getCampaignLabelServiceClient();
        $response = $campaignLabelServiceClient->mutateCampaignLabels(
            MutateCampaignLabelsRequest::build($customerId, $operations)
        );

        printf("Added %d campaign labels:%s", $response->getResults()->count(), PHP_EOL);

        foreach ($response->getResults() as $addedCampaignLabel) {
            /**
 * @var CampaignLabel $addedCampaignLabel
*/
            printf(
                "New campaign label added with resource name: '%s'.%s",
                $addedCampaignLabel->getResourceName(),
                PHP_EOL
            );
        }
    }
      
```

### Python

```python
def main(
    client: GoogleAdsClient,
    customer_id: str,
    label_id: str,
    campaign_ids: List[str],
) -> None:
    """This code example adds a campaign label to a list of campaigns.

    Args:
        client: An initialized GoogleAdsClient instance.
        customer_id: A client customer ID str.
        label_id: The ID of the label to attach to campaigns.
        campaign_ids: A list of campaign IDs to which the label will be added.
    """

    # Get an instance of CampaignLabelService client.
    campaign_label_service: CampaignLabelServiceClient = client.get_service(
        "CampaignLabelService"
    )
    campaign_service: CampaignServiceClient = client.get_service(
        "CampaignService"
    )
    label_service: LabelServiceClient = client.get_service("LabelService")

    # Build the resource name of the label to be added across the campaigns.
    label_resource_name: str = label_service.label_path(customer_id, label_id)

    operations: List[Any] = []

    for campaign_id in campaign_ids:
        campaign_resource_name: str = campaign_service.campaign_path(
            customer_id, campaign_id
        )
        campaign_label_operation: Any = client.get_type(
            "CampaignLabelOperation"
        )

        campaign_label: CampaignLabel = campaign_label_operation.create
        campaign_label.campaign = campaign_resource_name
        campaign_label.label = label_resource_name
        operations.append(campaign_label_operation)

    response: MutateCampaignLabelsResponse = (
        campaign_label_service.mutate_campaign_labels(
            customer_id=customer_id, operations=operations
        )
    )
    print(f"Added {len(response.results)} campaign labels:")
    for result in response.results:
        print(result.resource_name)
      
```

### Ruby

```ruby
def add_campaign_label(customer_id, label_id, campaign_ids)
  # GoogleAdsClient will read a config file from
  # ENV['HOME']/google_ads_config.rb when called without parameters
  client = Google::Ads::GoogleAds::GoogleAdsClient.new

  label_resource_name = client.path.label(customer_id, label_id)

  labels = campaign_ids.map { |campaign_id|
    client.resource.campaign_label do |label|
      campaign_resource_name = client.path.campaign(customer_id, campaign_id)
      label.campaign = campaign_resource_name
      label.label = label_resource_name
    end
  }

  ops = labels.map { |label|
    client.operation.create_resource.campaign_label(label)
  }

  response = client.service.campaign_label.mutate_campaign_labels(
    customer_id: customer_id,
    operations: ops,
  )
  response.results.each do |result|
    puts("Created campaign label with id: #{result.resource_name}")
  end
end
      
```

### Perl

```perl
sub add_campaign_labels {
  my ($api_client, $customer_id, $campaign_ids, $label_id) = @_;

  my $label_resource_name =
    Google::Ads::GoogleAds::V26::Utils::ResourceNames::label($customer_id,
    $label_id);

  my $campaign_label_operations = [];

  # Create a campaign label operation for each campaign.
  foreach my $campaign_id (@$campaign_ids) {
    # Create a campaign label.
    my $campaign_label =
      Google::Ads::GoogleAds::V26::Resources::CampaignLabel->new({
        campaign => Google::Ads::GoogleAds::V26::Utils::ResourceNames::campaign(
          $customer_id, $campaign_id
        ),
        label => $label_resource_name
      });

    # Create a campaign label operation.
    my $campaign_label_operation =
      Google::Ads::GoogleAds::V26::Services::CampaignLabelService::CampaignLabelOperation
      ->new({
        create => $campaign_label
      });

    push @$campaign_label_operations, $campaign_label_operation;
  }

  # Add the campaign labels to the campaigns.
  my $campaign_labels_response = $api_client->CampaignLabelService()->mutate({
    customerId => $customer_id,
    operations => $campaign_label_operations
  });

  my $campaign_label_results = $campaign_labels_response->{results};
  printf "Added %d campaign labels:\n", scalar @$campaign_label_results;

  foreach my $campaign_label_result (@$campaign_label_results) {
    printf "Created campaign label '%s'.\n",
      $campaign_label_result->{resourceName};
  }

  return 1;
}
      
```

### 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 />

### Assign labels to customers

Assigning labels to a customer is a common task for manager accounts to
categorize their client accounts. This is performed using
[`CustomerLabelService`](https://developers.google.com/google-ads/api/reference/rpc/v26/CustomerLabelService.md.txt). Labels created by
a manager account are owned by that manager account and are visible only when
authenticated as the owning manager account.

Each [`CustomerLabelOperation`](https://developers.google.com/google-ads/api/reference/rpc/v26/CustomerLabelOperation.md.txt) includes a
[`CustomerLabel`](https://developers.google.com/google-ads/api/reference/rpc/v26/CustomerLabel.md.txt) instance. When creating a
customer-label relationship, keep in mind:

- `label`: This field is required and must be the resource name of a label owned by the manager account, such as `customers/{MANAGER_ID}/labels/{LABEL_ID}`.
- `customer`: This field is output-only and shouldn't be set in the request. The customer being labeled is determined by the `customer_id` in the `MutateCustomerLabelsRequest` path.

> [!NOTE]
> **Note:** A single `MutateCustomerLabelsRequest` can only modify labels for the single client account specified in the request. To apply a label to multiple client accounts, you must make separate API calls for each account.

## Retrieve objects using their labels

After you've assigned labels to your campaigns, you can use the
[label fields](https://developers.google.com/google-ads/api/fields/v26/label.md.txt) to retrieve objects by ID.

Pass an appropriate [GAQL](https://developers.google.com/google-ads/api/docs/query/overview.md.txt) query to a
[`GoogleAdsService`](https://developers.google.com/google-ads/api/reference/rpc/v26/GoogleAdsService.md.txt) `Search` or `SearchStream`
request. For example, the following query returns the ID, name, and labels for
each campaign associated with any one of three label IDs:

```sql
SELECT
  campaign.id,
  campaign.name,
  label.id,
  label.name
FROM campaign_label
WHERE label.id IN (123456, 789012, 345678)
```

You can only filter by label ID, not label name. To get the label ID from a
label name, use this query:

```sql
SELECT
  label.id,
  label.name
FROM label
WHERE label.name = "LABEL_NAME"
```

## Retrieve labels applied to a customer

When [getting the hierarchy of accounts under a manager account](https://developers.google.com/google-ads/api/docs/account-management/get-account-hierarchy.md.txt),
you can retrieve the list of labels applied to a child customer account by
requesting the [`applied_labels`](https://developers.google.com/google-ads/api/reference/rpc/v26/CustomerClient.md.txt#applied_labels%5B%5D) field from the
[`CustomerClient`](https://developers.google.com/google-ads/api/reference/rpc/v26/CustomerClient.md.txt) object. This field retrieves
only the labels owned by the customer making the API call.

## Use labels in reports

Use labels to improve the usefulness of your reports.

### Labels reporting

The [Label](https://developers.google.com/google-ads/api/fields/v26/label.md.txt) report resource returns details about the labels
defined in an account. Details include the name, ID, resource name, status,
background color, and description, as well as the [Customer](https://developers.google.com/google-ads/api/fields/v26/customer.md.txt)
resource representing the label's owner.

### Reports with metrics

The [Ad Group](https://developers.google.com/google-ads/api/fields/v26/ad_group.md.txt) and [Campaign](https://developers.google.com/google-ads/api/fields/v26/campaign.md.txt) report
views contain the `labels` field. The reporting service returns the label
resource names in the format `customers/{customer_id}/labels/{label_id}`. For
example, the resource name `customers/123456789/labels/012345` refers to the
label with ID `012345` in the account with ID `123456789`.

### Reports without metrics

Each of the following report resources can be used to find relationships between
resources and labels:

- [Ad Group Ad Label](https://developers.google.com/google-ads/api/fields/v26/ad_group_ad_label.md.txt)
- [Ad Group Criterion Label](https://developers.google.com/google-ads/api/fields/v26/ad_group_criterion_label.md.txt)
- [Ad Group Label](https://developers.google.com/google-ads/api/fields/v26/ad_group_label.md.txt)
- [Campaign Label](https://developers.google.com/google-ads/api/fields/v26/campaign_label.md.txt)
- [Customer Label](https://developers.google.com/google-ads/api/fields/v26/customer_label.md.txt)

You can filter these report results by comparing the `label.id` field using any
numeric comparison operator or the `BETWEEN`, `IS NULL`, `IS NOT NULL`, `IN`, or
`NOT IN` operators.

In this example, you can get all campaigns with a specific label ID:

```sql
SELECT
  campaign.id,
  campaign.name,
  label.id,
  label.name
FROM campaign_label
WHERE label.id = LABEL_ID
ORDER BY campaign.id
```