Create Ads

Add expanded text ad

The best way to set up new ads in the API is to use the Add Expanded Text Ads code example in the Basic Operations folder of your client library. The sample handles all the background authentication tasks for you, and walks you through creating expanded text ads.

Java

private void runExample(GoogleAdsClient googleAdsClient, long customerId, long adGroupId) {

  String adGroupResourceName = ResourceNames.adGroup(customerId, adGroupId);

  List<AdGroupAdOperation> operations = new ArrayList<>();

  for (int i = 0; i < NUMBER_OF_ADS_TO_ADD; i++) {

    // Creates the expanded text ad info.
    ExpandedTextAdInfo expandedTextAdInfo =
        ExpandedTextAdInfo.newBuilder()
            .setHeadlinePart1(String.format("Cruise #%d to Mars", i))
            .setHeadlinePart2("Best Space Cruise Line")
            .setDescription("Buy your tickets now!")
            .build();

    // Wraps the info in an Ad object.
    Ad ad =
        Ad.newBuilder()
            .setExpandedTextAd(expandedTextAdInfo)
            .addFinalUrls("http://www.example.com")
            .build();

    // Builds the final ad group ad representation.
    AdGroupAd adGroupAd =
        AdGroupAd.newBuilder()
            .setAdGroup(adGroupResourceName)
            .setStatus(AdGroupAdStatus.PAUSED)
            .setAd(ad)
            .build();

    AdGroupAdOperation op = AdGroupAdOperation.newBuilder().setCreate(adGroupAd).build();
    operations.add(op);
  }

  try (AdGroupAdServiceClient adGroupAdServiceClient =
      googleAdsClient.getLatestVersion().createAdGroupAdServiceClient()) {
    MutateAdGroupAdsResponse response =
        adGroupAdServiceClient.mutateAdGroupAds(Long.toString(customerId), operations);
    for (MutateAdGroupAdResult result : response.getResultsList()) {
      System.out.printf(
          "Expanded text ad created with resource name: %s%n", result.getResourceName());
    }
  }
}

C#

public void Run(GoogleAdsClient client, long customerId, long adGroupId)
{
    // Get the AdGroupAdService.
    AdGroupAdServiceClient adGroupAdService = client.GetService(
        Services.V5.AdGroupAdService);

    List<AdGroupAdOperation> operations = new List<AdGroupAdOperation>();
    for (int i = 0; i < NUMBER_OF_ADS; i++)
    {
        // Create the ad group ad object.
        AdGroupAd adGroupAd = new AdGroupAd
        {
            AdGroup = ResourceNames.AdGroup(customerId, adGroupId),
            // Optional: Set the status.
            Status = AdGroupAdStatus.Paused,
            Ad = new Ad
            {
                FinalUrls = { "http://www.example.com/" + i },
                ExpandedTextAd = new ExpandedTextAdInfo
                {
                    Description = "Buy your tickets now!",
                    HeadlinePart1 = "Cruise #" + i.ToString() + " to Mars",
                    HeadlinePart2 = "Best Space Cruise Line",
                    Path1 = "path1",
                    Path2 = "path2"
                }
            }
        };

        // Create the operation.
        operations.Add(new AdGroupAdOperation
        {
            Create = adGroupAd
        });
    }

    try
    {
        // Create the ads.
        MutateAdGroupAdsResponse response = adGroupAdService.MutateAdGroupAds(
            customerId.ToString(), operations);

        // Display the results.
        foreach (MutateAdGroupAdResult result in response.Results)
        {
            Console.WriteLine("Expanded text ad created with resource name: {0}",
                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,
    int $adGroupId
) {
    $operations = [];
    for ($i = 0; $i < self::NUMBER_OF_ADS_TO_ADD; $i++) {
        // Creates the expanded text ad info.
        $expandedTextAdInfo = new ExpandedTextAdInfo([
            'headline_part1' => 'Cruise to Mars #' . uniqid(),
            'headline_part2' => 'Best Space Cruise Line',
            'description' => 'Buy your tickets now!'
        ]);

        // Sets the expanded text ad info on an Ad.
        $ad = new Ad([
            'expanded_text_ad' => $expandedTextAdInfo,
            'final_urls' => ['http://www.example.com']
        ]);

        // Creates an ad group ad to hold the above ad.
        $adGroupAd = new AdGroupAd([
            'ad_group' => ResourceNames::forAdGroup($customerId, $adGroupId),
            'status' => AdGroupAdStatus::PAUSED,
            'ad' => $ad
        ]);

        // Creates an ad group ad operation and add it to the operations array.
        $adGroupAdOperation = new AdGroupAdOperation();
        $adGroupAdOperation->setCreate($adGroupAd);
        $operations[] = $adGroupAdOperation;
    }

    // Issues a mutate request to add the ad group ads.
    $adGroupAdServiceClient = $googleAdsClient->getAdGroupAdServiceClient();
    $response = $adGroupAdServiceClient->mutateAdGroupAds($customerId, $operations);

    foreach ($response->getResults() as $addedAdGroupAd) {
        /** @var AdGroupAd $addedAdGroupAd */
        printf(
            "Expanded text ad was created with resource name: '%s'%s",
            $addedAdGroupAd->getResourceName(),
            PHP_EOL
        );
    }
}

Python

def main(client, customer_id, ad_group_id, number_of_ads):
    ad_group_ad_service = client.get_service("AdGroupAdService", version="v5")
    ad_group_service = client.get_service("AdGroupService", version="v5")

    ad_group_ad_operations = []

    for i in range(number_of_ads):

        # Create ad group ad.
        ad_group_ad_operation = client.get_type(
            "AdGroupAdOperation", version="v5"
        )
        ad_group_ad = ad_group_ad_operation.create
        ad_group_ad.ad_group = ad_group_service.ad_group_path(
            customer_id, ad_group_id
        )
        ad_group_ad.status = client.get_type(
            "AdGroupAdStatusEnum", version="v5"
        ).PAUSED

        # Set expanded text ad info
        ad_group_ad.ad.final_urls.append("http://www.example.com")
        ad_group_ad.ad.expanded_text_ad.description = "Buy your tickets now!"
        ad_group_ad.ad.expanded_text_ad.headline_part1 = "Cruise {} to Mars {}".format(
            i, str(uuid.uuid4())[:8]
        )
        ad_group_ad.ad.expanded_text_ad.headline_part2 = (
            "Best space cruise line"
        )
        ad_group_ad.ad.expanded_text_ad.path1 = "all-inclusive"
        ad_group_ad.ad.expanded_text_ad.path2 = "deals"

        ad_group_ad_operations.append(ad_group_ad_operation)

    try:
        ad_group_ad_response = ad_group_ad_service.mutate_ad_group_ads(
            customer_id, ad_group_ad_operations
        )
    except google.ads.google_ads.errors.GoogleAdsException as ex:
        print(
            'Request with ID "{}" failed with status "{}" and includes the '
            "following errors:".format(ex.request_id, ex.error.code().name)
        )
        for error in ex.failure.errors:
            print('\tError with message "{}".'.format(error.message))
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(
                        "\t\tOn field: {}".format(field_path_element.field_name)
                    )
        sys.exit(1)

    for result in ad_group_ad_response.results:
        print("Created ad group ad {}.".format(result.resource_name))

Ruby

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

  # Create an ad group ad.
  ad_group_ad = client.resource.ad_group_ad do |aga|
    aga.ad_group = client.path.ad_group(customer_id, ad_group_id)
    aga.status = :PAUSED
    aga.ad = client.resource.ad do |ad|
      ad.final_urls << "http://www.example.com"

      # Set expanded text ad info
      ad.expanded_text_ad = client.resource.expanded_text_ad_info do |eta|
        eta.description = "Buy your tickets now!"
        eta.headline_part1 = "Cruise to Mars #{(Time.new.to_f * 100).to_i}"
        eta.headline_part2 = "Best Space Cruise Line"
        eta.path1 = "all-inclusive"
        eta.path2 = "deals"
      end
    end
  end

  # Create the operation.
  ad_group_ad_operation = client.operation.create_resource.ad_group_ad(ad_group_ad)

  # Add the ad group ad.
  response = client.service.ad_group_ad.mutate_ad_group_ads(
    customer_id: customer_id,
    operations: [ad_group_ad_operation],
  )

  puts "Created expanded text ad #{response.results.first.resource_name}."
end

Perl

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

  # Create an expanded text ad info.
  my $expanded_text_ad_info =
    Google::Ads::GoogleAds::V5::Common::ExpandedTextAdInfo->new({
      description   => "Buy your tickets now!",
      headlinePart1 => "Cruise to Mars " . uniqid,
      headlinePart2 => "Best Space Cruise Line",
      path1         => "all-inclusive",
      path2         => "deals"
    });

  # Create an ad group ad.
  my $ad_group_ad = Google::Ads::GoogleAds::V5::Resources::AdGroupAd->new({
      adGroup => Google::Ads::GoogleAds::V5::Utils::ResourceNames::ad_group(
        $customer_id, $ad_group_id
      ),
      status => PAUSED,
      ad     => Google::Ads::GoogleAds::V5::Resources::Ad->new({
          expandedTextAd => $expanded_text_ad_info,
          finalUrls      => "http://www.example.com"
        })});

  # Create an ad group ad operation.
  my $ad_group_ad_operation =
    Google::Ads::GoogleAds::V5::Services::AdGroupAdService::AdGroupAdOperation
    ->new({create => $ad_group_ad});

  # Add the ad group ad.
  my $ad_group_ad_response = $api_client->AdGroupAdService()->mutate({
      customerId => $customer_id,
      operations => [$ad_group_ad_operation]});

  printf "Created expanded text ad '%s'.\n",
    $ad_group_ad_response->{results}[0]{resourceName};

  return 1;
}