Labels

Labels allow you to 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:

This guide focuses on campaigns, but you can use the same approach for ad groups, ads, and keywords. Note that the API also provides CustomerLabelService, which allows Manager accounts to assign labels to child accounts.

Use cases

Typical scenarios for using labels include:

  • Your account has campaigns you enable only during certain times of the year, and you want to easily 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 an easy way to identify the set of campaigns for each user.
  • Your application needs to mark the status of certain objects as processed, audited, highlighted, etc.

See the Help Center article on using labels for additional information and an example of how labels work in Google Ads.

Create labels

You create labels using the TextLabel object. To create a TextLabel:

  1. Create a TextLabel instance.
  2. Set a background color for this TextLabel.
  3. Enter text for this TextLabel using the description field.
  4. Wrap the TextLabel in a LabelOperation and send it to LabelService.MutateLabels.

You'll need the IDs of the new labels for the next steps. These are embedded in the resource_name field in the MutateLabelResults returned in the MutateLabelsResponse. Alternatively, use a LabelService.GetLabel request or a GoogleAdsService Search or SearchStream request to retrieve the IDs.

Assign labels

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

For example, to assign labels to a campaign, pass one or more CampaignLabelOperation to CampaignLabelService.MutateCampaignLabels. Each CampaignLabelOperation includes a CampaignLabel instance, which contains:

  • label - The ID of a label.
  • campaign - The ID of a campaign.

You will need to create a CampaignLabel instance for each label/campaign pair, wrap it in a CampaignLabelOperation with the create operation, and send it to CampaignService.MutateCampaignLabels.

Retrieve objects using their labels

Now that you've assigned labels to your campaigns, you can use the label fields to retrieve objects that have one or more specific labels. You can do so by passing an appropriate GAQL query to a GoogleAdsService Search or SearchStream request.

For example, the following statement will return the ID, name, and labels for each campaign associated with any one of three label IDs:

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

Note that you should filter by label ID, not label name.

Retrieve labels applied to a customer

When getting the hierarchy of accounts under a manager account, you can retrieve the list of labels applied to a child customer account by requesting the applied_labels field from the CustomerClient object. This field retrieves only the labels owned by the customer making the API call.

Use labels in reports

Labels reporting

The Label 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 resource representing the label's owner.

Reports with metrics

The Ad Group and Campaign 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 would refer 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:

You can filter the above 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.

Code examples

The Campaign Management folder of each client library contains code examples for adding labels to campaigns and retrieving campaigns by label.

Add campaign labels

These examples demonstrate how to add a campaign label to a list of campaigns.

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#

public void Run(GoogleAdsClient client, long customerId, long[] campaignIds, long labelId)
{
    // Get the CampaignLabelServiceClient.
    CampaignLabelServiceClient campaignLabelService =
        client.GetService(Services.V13.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

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(
        $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

def main(client, customer_id, label_id, campaign_ids):
    """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 = client.get_service("CampaignLabelService")
    campaign_service = client.get_service("CampaignService")
    label_service = client.get_service("LabelService")

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

    operations = []

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

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

    response = 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

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

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

  my $label_resource_name =
    Google::Ads::GoogleAds::V13::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::V13::Resources::CampaignLabel->new({
        campaign => Google::Ads::GoogleAds::V13::Utils::ResourceNames::campaign(
          $customer_id, $campaign_id
        ),
        label => $label_resource_name
      });

    # Create a campaign label operation.
    my $campaign_label_operation =
      Google::Ads::GoogleAds::V13::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;
}
      

Get campaigns by label

These examples demonstrate how to get all campaigns with a specific label.

Java

private void runExample(GoogleAdsClient googleAdsClient, long customerId, long labelId) {
  try (GoogleAdsServiceClient googleAdsServiceClient =
      googleAdsClient.getLatestVersion().createGoogleAdsServiceClient()) {
    // Creates a request that will retrieve all campaign labels with the specified
    // labelId using pages of the specified page size.
    SearchGoogleAdsRequest request =
        SearchGoogleAdsRequest.newBuilder()
            .setCustomerId(Long.toString(customerId))
            .setPageSize(PAGE_SIZE)
            .setQuery(
                "SELECT campaign.id, campaign.name, label.id, label.name "
                    + "FROM campaign_label WHERE label.id = "
                    + labelId
                    + " ORDER BY campaign.id")
            .build();
    // Issues the search request.
    SearchPagedResponse searchPagedResponse = googleAdsServiceClient.search(request);
    // Checks if the total results count is greater than 0.
    if (searchPagedResponse.getPage().getResponse().getTotalResultsCount() > 0) {
      // Iterates over all rows in all pages and prints the requested field values for the
      // campaigns and labels in each row. The results include the campaign and label
      // objects because these were included in the search criteria.
      for (GoogleAdsRow googleAdsRow : searchPagedResponse.iterateAll()) {
        System.out.printf(
            "Campaign found with name '%s', ID %d, and label: %s.%n",
            googleAdsRow.getCampaign().getName(),
            googleAdsRow.getCampaign().getId(),
            googleAdsRow.getLabel().getName());
      }
    } else {
      System.out.println("No campaigns were found.");
    }
  }
}
      

C#

public void Run(GoogleAdsClient client, long customerId, long labelId)
{
    // Get the GoogleAdsServiceClient.
    GoogleAdsServiceClient googleAdsService =
        client.GetService(Services.V13.GoogleAdsService);

    // Creates a request that will retrieve all campaign labels with the specified
    // labelId using pages of the specified page size.
    SearchGoogleAdsRequest request = new SearchGoogleAdsRequest()
    {
        CustomerId = customerId.ToString(),
        Query = "SELECT campaign.id, campaign.name, label.id, label.name " +
            $"FROM campaign_label WHERE label.id = {labelId} ORDER BY campaign.id",
    };

    try
    {
        int count = 0;
        // Issues the search request and prints the result.
        foreach (GoogleAdsRow googleAdsRow in googleAdsService.Search(request))
        {
            count++;
            Console.WriteLine($"Campaign found with name '{googleAdsRow.Campaign.Name}'" +
                $", ID {googleAdsRow.Campaign.Id}, and label: " +
                $"'${googleAdsRow.Label.Name}'.");
        }
        if (count == 0)
        {
            Console.WriteLine("No campaigns were found.");
        }
    }
    catch (GoogleAdsException e)
    {
        Console.WriteLine("Failure:");
        Console.WriteLine($"Message: {e.Message}");
        Console.WriteLine($"Failure: {e.Failure}");
        Console.WriteLine($"Request ID: {e.RequestId}");
        throw;
    }
}
      

PHP

public static function runExample(
    GoogleAdsClient $googleAdsClient,
    int $customerId,
    int $labelId
) {
    $googleAdsServiceClient = $googleAdsClient->getGoogleAdsServiceClient();
    // Creates a query that will retrieve all campaign labels with the specified
    // label ID.
    $query = "SELECT campaign.id, campaign.name, label.id, label.name " .
        "FROM campaign_label WHERE label.id = $labelId ORDER BY campaign.id";
    // Issues a search request by specifying page size.
    $response =
        $googleAdsServiceClient->search($customerId, $query, ['pageSize' => self::PAGE_SIZE]);

    // Iterates over all rows in all pages and prints the requested field values for the
    // campaigns and labels in each row. The results include the campaign and label
    // objects because these were included in the search criteria.
    foreach ($response->iterateAllElements() as $googleAdsRow) {
        /** @var GoogleAdsRow $googleAdsRow */
        printf(
            "Campaign found with name '%s', ID %d, and label: '%s'.%s",
            $googleAdsRow->getCampaign()->getName(),
            $googleAdsRow->getCampaign()->getId(),
            $googleAdsRow->getLabel()->getName(),
            PHP_EOL
        );
    }
}
      

Python

def main(client, customer_id, label_id, page_size):
    """Demonstrates how to retrieve all campaigns by a given label ID.

    Args:
        client: An initialized GoogleAdsClient instance.
        customer_id: A client customer ID str.
        label_id: A label ID to use when searching for campaigns.
        page_size: An int of the number of results to include in each page of
            results.
    """
    ga_service = client.get_service("GoogleAdsService")

    # Creates a query that will retrieve all campaign labels with the
    # specified label ID.
    query = f"""
        SELECT
            campaign.id,
            campaign.name,
            label.id,
            label.name
         FROM campaign_label
         WHERE label.id = "{label_id}"
         ORDER BY campaign.id"""

    # Retrieves a google.api_core.page_iterator.GRPCIterator instance
    # initialized with the specified request parameters.
    request = client.get_type("SearchGoogleAdsRequest")
    request.customer_id = customer_id
    request.query = query
    request.page_size = page_size

    iterator = ga_service.search(request=request)

    # Iterates over all rows in all pages and prints the requested field
    # values for the campaigns and labels in each row. The results include
    # the campaign and label objects because these were included in the
    # search criteria.
    for row in iterator:
        print(
            f'Campaign found with ID "{row.campaign.id}", name '
            f'"{row.campaign.name}", and label "{row.label.name}".'
        )


if __name__ == "__main__":
    # GoogleAdsClient will read the google-ads.yaml configuration file in the
    # home directory if none is specified.
    googleads_client = GoogleAdsClient.load_from_storage(version="v13")

    parser = argparse.ArgumentParser(
        description="Lists all campaigns for specified customer."
    )
    # The following argument(s) should be provided to run the example.
    parser.add_argument(
        "-c",
        "--customer_id",
        type=str,
        required=True,
        help="The Google Ads customer ID.",
    )
    parser.add_argument(
        "-l",
        "--label_id",
        type=str,
        required=True,
        help="A label ID associated with a campaign.",
    )
    args = parser.parse_args()

    try:
        main(
            googleads_client,
            args.customer_id,
            args.label_id,
            _DEFAULT_PAGE_SIZE,
        )
    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'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)

      

Ruby

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

  query = <<~EOQUERY
    SELECT campaign.id, campaign.name, label.id, label.name
    FROM campaign_label WHERE label.id = '#{label_id}' ORDER BY campaign.id
  EOQUERY

  ga_service = client.service.google_ads
  response = ga_service.search(
    customer_id: customer_id,
    query: query,
    page_size: PAGE_SIZE,
  )

  response.each do |row|
    puts "Campaign with ID #{row.campaign.id} and name '#{row.campaign.name}' was found."
  end
end
      

Perl

sub get_campaigns_by_label {
  my ($api_client, $customer_id, $label_id) = @_;

  # Create the search query.
  my $search_query =
    "SELECT campaign.id, campaign.name, label.id, label.name " .
    "FROM campaign_label WHERE label.id = $label_id ORDER BY campaign.id";

  # Create a search Google Ads request that will retrieve all campaign labels
  # with the specified label Id using pages of the specified page size.
  my $search_request =
    Google::Ads::GoogleAds::V13::Services::GoogleAdsService::SearchGoogleAdsRequest
    ->new({
      customerId => $customer_id,
      query      => $search_query,
      pageSize   => PAGE_SIZE
    });

  # Get the GoogleAdsService.
  my $google_ads_service = $api_client->GoogleAdsService();

  my $iterator = Google::Ads::GoogleAds::Utils::SearchGoogleAdsIterator->new({
    service => $google_ads_service,
    request => $search_request
  });

  # Iterate over all rows in all pages and print the requested field values for the
  # campaigns and labels in each row. The results include the campaign and label
  # objects because these were included in the search criteria.
  while ($iterator->has_next) {
    my $google_ads_row = $iterator->next;

    printf "Campaign found with name '%s', ID %d, and label: '%s'.\n",
      $google_ads_row->{campaign}{name}, $google_ads_row->{campaign}{id},
      $google_ads_row->{label}{name};
  }

  return 1;
}