Register for one of our Google Ads API Migration Workshops (October 5, 2021 - October 14, 2021)

Add Custom Audience

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

package com.google.ads.googleads.examples.remarketing;

import static com.google.ads.googleads.examples.utils.CodeSampleHelper.getPrintableDateTime;

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.v8.enums.CustomAudienceMemberTypeEnum.CustomAudienceMemberType;
import com.google.ads.googleads.v8.enums.CustomAudienceStatusEnum.CustomAudienceStatus;
import com.google.ads.googleads.v8.enums.CustomAudienceTypeEnum.CustomAudienceType;
import com.google.ads.googleads.v8.errors.GoogleAdsError;
import com.google.ads.googleads.v8.errors.GoogleAdsException;
import com.google.ads.googleads.v8.resources.CustomAudience;
import com.google.ads.googleads.v8.resources.CustomAudienceMember;
import com.google.ads.googleads.v8.services.CustomAudienceOperation;
import com.google.ads.googleads.v8.services.CustomAudienceServiceClient;
import com.google.ads.googleads.v8.services.MutateCustomAudiencesResponse;
import com.google.common.collect.ImmutableList;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Illustrates adding a custom audience. Custom audiences help you reach your ideal audience by
 * entering relevant keywords, URLs and apps. For more information about custom audiences, see:
 * https://support.google.com/google-ads/answer/9805516.
 */
public class AddCustomAudience {

  private static class AddCustomAudienceParams extends CodeSampleParams {

    @Parameter(names = ArgumentNames.CUSTOMER_ID, required = true)
    private Long customerId;
  }

  public static void main(String[] args) {
    AddCustomAudienceParams params = new AddCustomAudienceParams();
    if (!params.parseArguments(args)) {

      // Either pass the required parameters for this example on the command line, or insert them
      // into the code here. See the parameter class definition above for descriptions.
      params.customerId = Long.parseLong("INSERT_CUSTOMER_ID_HERE");
    }

    GoogleAdsClient googleAdsClient = null;
    try {
      googleAdsClient = GoogleAdsClient.newBuilder().fromPropertiesFile().build();
    } catch (FileNotFoundException fnfe) {
      System.err.printf(
          "Failed to load GoogleAdsClient configuration from file. Exception: %s%n", fnfe);
      System.exit(1);
    } catch (IOException ioe) {
      System.err.printf("Failed to create GoogleAdsClient. Exception: %s%n", ioe);
      System.exit(1);
    }

    try {
      new AddCustomAudience().runExample(googleAdsClient, params.customerId);
    } catch (GoogleAdsException gae) {
      // GoogleAdsException is the base class for most exceptions thrown by an API request.
      // Instances of this exception have a message and a GoogleAdsFailure that contains a
      // collection of GoogleAdsErrors that indicate the underlying causes of the
      // GoogleAdsException.
      System.err.printf(
          "Request ID %s failed due to GoogleAdsException. Underlying errors:%n",
          gae.getRequestId());
      int i = 0;
      for (GoogleAdsError googleAdsError : gae.getGoogleAdsFailure().getErrorsList()) {
        System.err.printf("  Error %d: %s%n", i++, googleAdsError);
      }
      System.exit(1);
    }
  }

  /** Runs the example. */
  private void runExample(GoogleAdsClient googleAdsClient, long customerId) {
    // Creates a CustomAudience object to represent the new audience.
    CustomAudience customAudience =
        CustomAudience.newBuilder()
            .setName("Example CustomAudience #" + getPrintableDateTime())
            .setDescription("Custom audiences who have searched specific terms on Google Search")
            // Matches customers by what they searched on Google Search.
            // Note: "INTEREST" OR "PURCHASE_INTENT" is not allowed for the type field
            //       of newly created custom audience. Use "AUTO" instead of these 2 options
            //       when creating a new custom audience.
            .setType(CustomAudienceType.SEARCH)
            .setStatus(CustomAudienceStatus.ENABLED)

            // Lists the members that this custom audience is composed of. Customers that meet any
            // of the membership conditions will be reached.

            // Adds Keywords or keyword phrases, which describe the customers' interests or search
            // terms.
            .addMembers(createCustomAudienceMember(CustomAudienceMemberType.KEYWORD, "mars cruise"))
            .addMembers(
                createCustomAudienceMember(CustomAudienceMemberType.KEYWORD, "jupiter cruise"))

            // Adds website URLs that your customers might visit.
            .addMembers(
                createCustomAudienceMember(
                    CustomAudienceMemberType.URL, "http://www.example.com/locations/mars"))
            .addMembers(
                createCustomAudienceMember(
                    CustomAudienceMemberType.URL, "http://www.example.com/locations/jupiter"))

            // Adds package names of Android apps which customers might install.
            .addMembers(
                createCustomAudienceMember(
                    CustomAudienceMemberType.APP, "com.google.android.apps.adwords"))
            .build();

    // Creates an operation to add the CustomAudience.
    CustomAudienceOperation operation =
        CustomAudienceOperation.newBuilder().setCreate(customAudience).build();

    // Creates an API client and send the mutate request.
    try (CustomAudienceServiceClient serviceClient =
        googleAdsClient.getLatestVersion().createCustomAudienceServiceClient()) {
      // Issues the mutate request.
      MutateCustomAudiencesResponse response =
          serviceClient.mutateCustomAudiences(
              String.valueOf(customerId), ImmutableList.of(operation));

      // Prints some information about the result.
      System.out.printf(
          "New custom audience added with resource name: '%s'.\n",
          response.getResults(0).getResourceName());
    }
  }

  /**
   * Constructs a {@link CustomAudienceMember} from a {@link CustomAudienceMemberType} and value for
   * the member type.
   */
  private static CustomAudienceMember createCustomAudienceMember(
      CustomAudienceMemberType memberType, String value) {
    CustomAudienceMember.Builder builder =
        CustomAudienceMember.newBuilder().setMemberType(memberType);
    if (memberType == CustomAudienceMemberType.KEYWORD) {
      builder.setKeyword(value);
    } else if (memberType == CustomAudienceMemberType.URL) {
      builder.setUrl(value);
    } else if (memberType == CustomAudienceMemberType.APP) {
      builder.setApp(value);
    }
    return builder.build();
  }
}

      
      

C#

// Copyright 2021 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.GoogleAds.Lib;
using Google.Ads.GoogleAds.V8.Errors;
using Google.Ads.GoogleAds.V8.Resources;
using Google.Ads.GoogleAds.V8.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using static Google.Ads.GoogleAds.V8.Enums.CustomAudienceMemberTypeEnum.Types;
using static Google.Ads.GoogleAds.V8.Enums.CustomAudienceStatusEnum.Types;
using static Google.Ads.GoogleAds.V8.Enums.CustomAudienceTypeEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V8
{
    /// <summary>
    /// This example illustrates adding a custom audience. Custom audiences help you reach your
    /// ideal audience by entering relevant keywords, URLs and apps. For more information about
    /// custom audiences, see:
    /// https://support.google.com/google-ads/answer/9805516.
    /// </summary>
    public class AddCustomAudience : ExampleBase
    {
        /// <summary>
        /// Command line options for running the <see cref="AddCustomAudience"/> example.
        /// </summary>
        public class Options : OptionsBase
        {
            /// <summary>
            /// The Google Ads customer ID for which the conversion action is added.
            /// </summary>
            [Option("customerId", Required = true, HelpText =
                "The Google Ads customer ID for which the conversion action is added.")]
            public long CustomerId { get; set; }
        }

        /// <summary>
        /// Main method, to run this code example as a standalone application.
        /// </summary>
        /// <param name="args">The command line arguments.</param>
        public static void Main(string[] args)
        {
            Options options = new Options();
            CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult(
                delegate (Options o)
                {
                    options = o;
                    return 0;
                }, delegate (IEnumerable<Error> errors)
                {
                    // The Google Ads customer ID for which the conversion action is added.
                    options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");

                    return 0;
                });

            AddCustomAudience codeExample = new AddCustomAudience();
            Console.WriteLine(codeExample.Description);
            codeExample.Run(new GoogleAdsClient(), options.CustomerId);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This example illustrates adding a custom audience. Custom audiences help you reach " +
            "your ideal audience by entering relevant keywords, URLs and apps. For more " +
            "information about custom audiences, see:" +
            "https://support.google.com/google-ads/answer/9805516.";

        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the conversion action is
        /// added.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            // Get the CustomAudienceService client.
            CustomAudienceServiceClient customAudienceServiceClient =
                client.GetService(Services.V8.CustomAudienceService);

            // Create a custom audience.
            CustomAudience customAudience = new CustomAudience
            {
                Name = $"Example CustomAudience #{ExampleUtilities.GetRandomString()}",
                Description = "Custom audiences who have searched specific terms on Google Search",
                // Match customers by what they searched on Google Search.
                // Note: "INTEREST" OR "PURCHASE_INTENT" is not allowed for the type field of newly
                // created custom audience. Use "AUTO" instead of these 2 options when creating a
                // new custom audience.
                Type = CustomAudienceType.Search,
                Status = CustomAudienceStatus.Enabled,
            };

            // Add custom audience members to the custom audience. Customers that meet any of the
            // membership conditions will be reached.
            // Keywords or keyword phrases, which describe the customers' interests or search terms.
            customAudience.Members.Add(CreateCustomAudienceMember(CustomAudienceMemberType.Keyword,
                "mars cruise"));
            customAudience.Members.Add(CreateCustomAudienceMember(CustomAudienceMemberType.Keyword,
                "jupiter cruise"));
            // Website URLs that your customers might visit.
            customAudience.Members.Add(CreateCustomAudienceMember(CustomAudienceMemberType.Url,
                "http://www.example.com/locations/mars"));
            customAudience.Members.Add(CreateCustomAudienceMember(CustomAudienceMemberType.Url,
                "http://www.example.com/locations/jupiter"));
            // Package names of Android apps which customers might install.
            customAudience.Members.Add(CreateCustomAudienceMember(CustomAudienceMemberType.App,
                "com.google.android.apps.adwords"));

            // Create a custom audience operation.
            CustomAudienceOperation customAudienceOperation = new CustomAudienceOperation
            {
                Create = customAudience
            };

            try
            {
                // Add the custom audience and display the results.
                MutateCustomAudiencesResponse customAudiencesResponse = customAudienceServiceClient
                    .MutateCustomAudiences(customerId.ToString(), new[] { customAudienceOperation });

                Console.WriteLine("New custom audience added with resource name: " +
                    $"'{customAudiencesResponse.Results.First().ResourceName}'.");
            }
            catch (GoogleAdsException e)
            {
                Console.WriteLine("Failure:");
                Console.WriteLine($"Message: {e.Message}");
                Console.WriteLine($"Failure: {e.Failure}");
                Console.WriteLine($"Request ID: {e.RequestId}");
                throw;
            }
        }

        /// <summary>
        /// Creates a custom audience member.
        /// </summary>
        /// <param name="memberType">The intended type of the new audience member.</param>
        /// <param name="value">The custom value to assign to the new audience member.</param>
        /// <returns></returns>
        public CustomAudienceMember CreateCustomAudienceMember(CustomAudienceMemberType memberType,
            string value)
        {
            CustomAudienceMember customAudienceMember = new CustomAudienceMember
            {
                MemberType = memberType
            };

            switch (memberType)
            {
                case CustomAudienceMemberType.Keyword:
                    customAudienceMember.Keyword = value;
                    break;

                case CustomAudienceMemberType.Url:
                    customAudienceMember.Url = value;
                    break;

                case CustomAudienceMemberType.App:
                    customAudienceMember.App = value;
                    break;
            }

            return customAudienceMember;
        }
    }
}

      
      

PHP

<?php

/**
 * Copyright 2021 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\Examples\Utils\Helper;
use Google\Ads\GoogleAds\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V8\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V8\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V8\GoogleAdsException;
use Google\Ads\GoogleAds\V8\Enums\CustomAudienceMemberTypeEnum\CustomAudienceMemberType;
use Google\Ads\GoogleAds\V8\Enums\CustomAudienceStatusEnum\CustomAudienceStatus;
use Google\Ads\GoogleAds\V8\Enums\CustomAudienceTypeEnum\CustomAudienceType;
use Google\Ads\GoogleAds\V8\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V8\Resources\CustomAudience;
use Google\Ads\GoogleAds\V8\Resources\CustomAudienceMember;
use Google\Ads\GoogleAds\V8\Services\CustomAudienceOperation;
use Google\ApiCore\ApiException;

/**
 * Illustrates adding a custom audience. Custom audiences help you reach your ideal audience by
 * entering relevant keywords, URLs and apps. For more information about custom audiences, see:
 * https://support.google.com/google-ads/answer/9805516.
 */
class AddCustomAudience
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';

    public static function main()
    {
        // Either pass the required parameters for this example on the command line, or insert them
        // into the constants above.
        $options = (new ArgumentParser())->parseCommandArguments([
            ArgumentNames::CUSTOMER_ID => GetOpt::REQUIRED_ARGUMENT
        ]);

        // Generate a refreshable OAuth2 credential for authentication.
        $oAuth2Credential = (new OAuth2TokenBuilder())->fromFile()->build();

        // Construct a Google Ads client configured from a properties file and the
        // OAuth2 credentials above.
        $googleAdsClient = (new GoogleAdsClientBuilder())
            ->fromFile()
            ->withOAuth2Credential($oAuth2Credential)
            ->build();

        try {
            self::runExample(
                $googleAdsClient,
                $options[ArgumentNames::CUSTOMER_ID] ?: self::CUSTOMER_ID
            );
        } catch (GoogleAdsException $googleAdsException) {
            printf(
                "Request with ID '%s' has failed.%sGoogle Ads failure details:%s",
                $googleAdsException->getRequestId(),
                PHP_EOL,
                PHP_EOL
            );
            foreach ($googleAdsException->getGoogleAdsFailure()->getErrors() as $error) {
                /** @var GoogleAdsError $error */
                printf(
                    "\t%s: %s%s",
                    $error->getErrorCode()->getErrorCode(),
                    $error->getMessage(),
                    PHP_EOL
                );
            }
            exit(1);
        } catch (ApiException $apiException) {
            printf(
                "ApiException was thrown with message '%s'.%s",
                $apiException->getMessage(),
                PHP_EOL
            );
            exit(1);
        }
    }

    /**
     * Runs the example.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     */
    public static function runExample(GoogleAdsClient $googleAdsClient, int $customerId)
    {
        // Creates a CustomAudience object to represent the new audience.
        $customAudience = new CustomAudience([
            'name' => 'Example CustomAudience #' . Helper::getPrintableDatetime(),
            'description' => 'Custom audiences who have searched specific terms on Google Search',
            // Matches customers by what they searched on Google Search.
            // Note: "INTEREST" OR "PURCHASE_INTENT" is not allowed for the type field
            //       of newly created custom audience. Use "AUTO" instead of these 2 options
            //       when creating a new custom audience.
            'type' => CustomAudienceType::SEARCH,
            'status' => CustomAudienceStatus::ENABLED,
            // Lists the members that this custom audience is composed of. Customers that meet any
            // of the membership conditions will be reached.
            'members' => [
                // Adds Keywords or keyword phrases, which describe the customers' interests or
                // search terms.
                self::createCustomAudienceMember(CustomAudienceMemberType::KEYWORD, "mars cruise"),
                self::createCustomAudienceMember(
                    CustomAudienceMemberType::KEYWORD,
                    "jupiter cruise"
                ),
                // Adds website URLs that your customers might visit.
                self::createCustomAudienceMember(
                    CustomAudienceMemberType::URL,
                    "http://www.example.com/locations/mars"
                ),
                self::createCustomAudienceMember(
                    CustomAudienceMemberType::URL,
                    "http://www.example.com/locations/jupiter"
                ),
                // Adds package names of Android apps which customers might install.
                self::createCustomAudienceMember(
                    CustomAudienceMemberType::APP,
                    "com.google.android.apps.adwords"
                )
            ]
        ]);

        // Creates the operation.
        $operation = new CustomAudienceOperation();
        $operation->setCreate($customAudience);

        // Issues a mutate request to add the custom audience and prints some information.
        $customAudienceServiceClient = $googleAdsClient->getCustomAudienceServiceClient();
        $response = $customAudienceServiceClient->mutateCustomAudiences($customerId, [$operation]);
        printf(
            "Created custom audience with resource name '%s'.%s",
            $response->getResults()[0]->getResourceName(),
            PHP_EOL
        );
    }

    /**
     * Constructs a custom audience member object for a given customer audience member type and
     * value.
     *
     * @param int $memberType the custom audience member type
     * @param string $value the custom audience member value
     * @return CustomAudienceMember the newly constructed customer audience member object
     */
    private static function createCustomAudienceMember(
        int $memberType,
        string $value
    ): CustomAudienceMember {
        $customerAudienceMember = new CustomAudienceMember(['member_type' => $memberType]);
        if ($memberType == CustomAudienceMemberType::KEYWORD) {
            $customerAudienceMember->setKeyword($value);
        } else if ($memberType == CustomAudienceMemberType::URL) {
            $customerAudienceMember->setUrl($value);
        } else if ($memberType == CustomAudienceMemberType::APP) {
            $customerAudienceMember->setApp($value);
        }
        return $customerAudienceMember;
    }
}

AddCustomAudience::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.
"""This example illustrates adding a custom audience.

Custom audiences help you reach your ideal audience by entering relevant
keywords, URLs, and apps. For more information about custom audiences, see:
https://support.google.com/google-ads/answer/9805516
"""


import argparse
import sys
from uuid import uuid4

from google.ads.googleads.client import GoogleAdsClient
from google.ads.googleads.errors import GoogleAdsException


def main(client, customer_id):
    """The main method that creates all necessary entities for the example.

    Args:
        client: an initialized GoogleAdsClient instance.
        customer_id: a client customer ID.
    """
    custom_audience_service = client.get_service("CustomAudienceService")

    # Create a custom audience operation.
    custom_audience_operation = client.get_type("CustomAudienceOperation")

    # Create a custom audience
    custom_audience = custom_audience_operation.create
    custom_audience.name = f"Example CustomAudience #{uuid4()}"
    custom_audience.description = (
        "Custom audiences who have searched specific terms on Google Search."
    )
    # Match customers by what they searched on Google Search. Note: "INTEREST"
    # or "PURCHASE_INTENT" is not allowed for the type field of a newly
    # created custom audience. Use "AUTO" instead of these two options when
    # creating a new custom audience.
    custom_audience.type_ = client.enums.CustomAudienceTypeEnum.SEARCH
    custom_audience.status = client.enums.CustomAudienceStatusEnum.ENABLED
    # List of members that this custom audience is composed of. Customers that
    # meet any of the membership conditions will be reached.
    member_type_enum = client.enums.CustomAudienceMemberTypeEnum

    member1 = _create_custom_audience_member(
        client, member_type_enum.KEYWORD, "mars cruise"
    )

    member2 = _create_custom_audience_member(
        client, member_type_enum.KEYWORD, "jupiter cruise"
    )

    member3 = _create_custom_audience_member(
        client, member_type_enum.URL, "http://www.example.com/locations/mars"
    )

    member4 = _create_custom_audience_member(
        client, member_type_enum.URL, "http://www.example.com/locations/jupiter"
    )

    member5 = _create_custom_audience_member(
        client, member_type_enum.APP, "com.google.android.apps.adwords"
    )

    custom_audience.members.extend(
        [member1, member2, member3, member4, member5]
    )

    # Add the custom audience.
    custom_audience_response = custom_audience_service.mutate_custom_audiences(
        customer_id=customer_id, operations=[custom_audience_operation]
    )

    print(
        "New custom audience added with resource name: "
        f"'{custom_audience_response.results[0].resource_name}'"
    )


def _create_custom_audience_member(client, member_type, value):
    """Creates a custom audience member for a given member type and value.

    Args:
        client: an initialized GoogleAdsClient instance.
        member_type: the custom audience member type.
        value: the custom audience member value.

    Returns:
        A newly created CustomAudienceMember.
    """
    member = client.get_type("CustomAudienceMember")
    member.member_type = member_type

    member_type_enum = client.enums.CustomAudienceMemberTypeEnum

    if member_type == member_type_enum.KEYWORD:
        member.keyword = value
    elif member_type == member_type_enum.URL:
        member.url = value
    elif member_type == member_type_enum.APP:
        member.app = value
    else:
        raise ValueError(
            "The member type must be a MemberTypeEnum value of KEYWORD, URL, or APP"
        )

    return member


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="v8")

    parser = argparse.ArgumentParser(
        description="Adds a custom audience for a 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.",
    )
    args = parser.parse_args()

    try:
        main(googleads_client, args.customer_id)
    except GoogleAdsException as ex:
        print(
            f'Request with ID "{ex.request_id}" failed with status '
            f'"{ex.error.code().name}" and includes the following errors:'
        )
        for error in ex.failure.errors:
            print(f'\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

#!/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 uses Customer Match to create a new user list (a.k.a. audience)
# and adds users to it.
#
# This example illustrates adding a custom audience. Custom audiences help you
# reach your ideal audience by entering relevant keywords, URLs and apps.
# For more information about custom audiences, see:
# https://support.google.com/google-ads/answer/9805516.

require 'optparse'
require 'google/ads/google_ads'
require 'date'
require 'digest'

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

  # Creates a custom audience operation.
  operation = client.operation.create_resource.custom_audience do |ca|
    ca.name = "Example Custom Audience ##{(Time.new.to_f * 1000).to_i}"
    ca.description = "Custom audiences who have searched specific terms on Google Search"
    # Match customers by what they searched on Google Search.
    # Note: "INTEREST" OR "PURCHASE_INTENT" is not allowed for the type field
    # of newly created custom audience. Use "AUTO" instead of these 2 options
    # when creating a new custom audience.
    ca.type = :SEARCH
    ca.status = :ENABLED
    # List of members that this custom audience is composed of. Customers that
    # meet any of the membership conditions will be reached.
    ca.members += [
      # Keywords or keyword phrases, which describe the customers' interests
      # or search terms.
      create_custom_audience_member(client, :KEYWORD, "Mars Cruise"),
      create_custom_audience_member(client, :KEYWORD, "Jupiter Cruise"),
      # Website URLs that your customers might visit.
      create_custom_audience_member(client, :URL, "http://www.example.com/locations/mars"),
      create_custom_audience_member(client, :URL, "http://www.example.com/locations/jupiter"),
      # Package names of Android apps which customers might install.
      create_custom_audience_member(client, :APP, "com.google.android.apps.adwords"),
    ]
  end

  # Issues a mutate request to add the custom audience.
  response = client.service.custom_audience.mutate_custom_audiences(
    customer_id: customer_id,
    operations: [operation],
  )
  puts "New custom audience added with resource name: " \
    "'#{response.results.first.resource_name}'."
end

# Creates a custom audience member.
def create_custom_audience_member(client, member_type, member_value)
  client.resource.custom_audience_member do |m|
    m.member_type = member_type
    case member_type
    when :KEYWORD
      m.keyword = member_value
    when :URL
      m.url = member_value
    when :APP
      m.app = member_value
    else
      raise "Invalid audience member type."
    end
  end
end

if __FILE__ == $0
  options = {}
  # The following parameter(s) should be provided to run the example. You can
  # either specify these by changing the INSERT_XXX_ID_HERE values below, or on
  # the command line.
  #
  # Parameters passed on the command line will override any parameters set in
  # code.
  #
  # Running the example with -h will print the command line usage.
  options[:customer_id] = 'INSERT_CUSTOMER_ID_HERE'

  OptionParser.new do |opts|
    opts.banner = sprintf('Usage: %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.separator ''
    opts.separator 'Help:'

    opts.on_tail('-h', '--help', 'Show this message') do
      puts opts
      exit
    end
  end.parse!

  begin
    add_custom_audience(options.fetch(:customer_id).tr("-", ""))
  rescue Google::Ads::GoogleAds::Errors::GoogleAdsError => e
    e.failure.errors.each do |error|
      STDERR.printf("Error with message: %s\n", error.message)
      if error.location
        error.location.field_path_elements.each do |field_path_element|
          STDERR.printf("\tOn 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("\tType: %s\n\tCode: %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 example illustrates adding a custom audience. Custom audiences help you
# reach your ideal audience by entering relevant keywords, URLs and apps. For more
# information about custom audiences, see:
# https://support.google.com/google-ads/answer/9805516.

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::V8::Resources::CustomAudience;
use Google::Ads::GoogleAds::V8::Resources::CustomAudienceMember;
use Google::Ads::GoogleAds::V8::Enums::CustomAudienceTypeEnum qw(SEARCH);
use Google::Ads::GoogleAds::V8::Enums::CustomAudienceStatusEnum qw(ENABLED);
use Google::Ads::GoogleAds::V8::Enums::CustomAudienceMemberTypeEnum
  qw(KEYWORD URL APP);
use
  Google::Ads::GoogleAds::V8::Services::CustomAudienceService::CustomAudienceOperation;

use Getopt::Long qw(:config auto_help);
use Pod::Usage;
use Cwd qw(abs_path);
use Data::Uniqid qw(uniqid);

# The following parameter(s) should be provided to run the example. You can
# either specify these by changing the INSERT_XXX_ID_HERE values below, or on
# the command line.
#
# Parameters passed on the command line will override any parameters set in
# code.
#
# Running the example with -h will print the command line usage.
my $customer_id = "INSERT_CUSTOMER_ID_HERE";

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

  # Create a custom audience.
  my $custom_audience =
    Google::Ads::GoogleAds::V8::Resources::CustomAudience->new({
      name        => "Example CustomAudience #" . uniqid(),
      description =>
        "Custom audiences who have searched specific terms on Google Search",
      # Match customers by what they searched on Google Search.
      # Note: "INTEREST" OR "PURCHASE_INTENT" is not allowed for the type field
      # of newly created custom audience. Use "AUTO" instead of these 2 options
      # when creating a new custom audience.
      type   => SEARCH,
      status => ENABLED,
      # List of members that this custom audience is composed of. Customers that
      # meet any of the membership conditions will be reached.
      members => [
        # Keywords or keyword phrases, which describe the customers' interests
        # or search terms.
        create_custom_audience_member(KEYWORD, "mars cruise"),
        create_custom_audience_member(KEYWORD, "jupiter cruise"),
        # Website URLs that your customers might visit.
        create_custom_audience_member(URL,
          "http://www.example.com/locations/mars"
        ),
        create_custom_audience_member(URL,
          "http://www.example.com/locations/jupiter"
        ),
        # Package names of Android apps which customers might install.
        create_custom_audience_member(APP, "com.google.android.apps.adwords"),
      ]});

  # Create a custom audience operation.
  my $custom_audience_operation =
    Google::Ads::GoogleAds::V8::Services::CustomAudienceService::CustomAudienceOperation
    ->new({create => $custom_audience});

  # Add the custom audience.
  my $custom_audiences_response = $api_client->CustomAudienceService()->mutate({
      customerId => $customer_id,
      operations => [$custom_audience_operation]});

  printf "New custom audience added with resource name: '%s'.\n",
    $custom_audiences_response->{results}[0]{resourceName};

  return 1;
}

# Creates a custom audience member.
sub create_custom_audience_member {
  my ($member_type, $value) = @_;
  my $custom_audience_member =
    Google::Ads::GoogleAds::V8::Resources::CustomAudienceMember->new({
      memberType => $member_type
    });

  if ($member_type eq KEYWORD) {
    $custom_audience_member->{keyword} = $value;
  } elsif ($member_type eq URL) {
    $custom_audience_member->{url} = $value;
  } elsif ($member_type eq APP) {
    $custom_audience_member->{app} = $value;
  }

  return $custom_audience_member;
}

# Don't run the example if the file is being included.
if (abs_path($0) ne abs_path(__FILE__)) {
  return 1;
}

# Get Google Ads Client, credentials will be read from ~/googleads.properties.
my $api_client = Google::Ads::GoogleAds::Client->new();

# By default examples are set to die on any server returned fault.
$api_client->set_die_on_faults(1);

# Parameters passed on the command line will override any parameters set in code.
GetOptions("customer_id=s" => \$customer_id);

# Print the help message if the parameters are not initialized in the code nor
# in the command line.
pod2usage(2) if not check_params($customer_id);

# Call the example.
add_custom_audience($api_client, $customer_id =~ s/-//gr);

=pod

=head1 NAME

add_custom_audience

=head1 DESCRIPTION

This example illustrates adding a custom audience. Custom audiences help you
reach your ideal audience by entering relevant keywords, URLs and apps. For more
information about custom audiences, see:
https://support.google.com/google-ads/answer/9805516.

=head1 SYNOPSIS

add_custom_audience.pl [options]

    -help                       Show the help message.
    -customer_id                The Google Ads customer ID.

=cut