Add Smart Display Ad

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

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

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.v5.common.AdImageAsset;
import com.google.ads.googleads.v5.common.AdTextAsset;
import com.google.ads.googleads.v5.common.ImageAsset;
import com.google.ads.googleads.v5.common.ResponsiveDisplayAdInfo;
import com.google.ads.googleads.v5.common.TargetCpa;
import com.google.ads.googleads.v5.enums.AdGroupAdStatusEnum.AdGroupAdStatus;
import com.google.ads.googleads.v5.enums.AdGroupStatusEnum.AdGroupStatus;
import com.google.ads.googleads.v5.enums.AdvertisingChannelSubTypeEnum.AdvertisingChannelSubType;
import com.google.ads.googleads.v5.enums.AdvertisingChannelTypeEnum.AdvertisingChannelType;
import com.google.ads.googleads.v5.enums.AssetTypeEnum.AssetType;
import com.google.ads.googleads.v5.enums.BudgetDeliveryMethodEnum.BudgetDeliveryMethod;
import com.google.ads.googleads.v5.errors.GoogleAdsError;
import com.google.ads.googleads.v5.errors.GoogleAdsException;
import com.google.ads.googleads.v5.resources.Ad;
import com.google.ads.googleads.v5.resources.AdGroup;
import com.google.ads.googleads.v5.resources.AdGroupAd;
import com.google.ads.googleads.v5.resources.Asset;
import com.google.ads.googleads.v5.resources.Campaign;
import com.google.ads.googleads.v5.resources.CampaignBudget;
import com.google.ads.googleads.v5.services.AdGroupAdOperation;
import com.google.ads.googleads.v5.services.AdGroupAdServiceClient;
import com.google.ads.googleads.v5.services.AdGroupOperation;
import com.google.ads.googleads.v5.services.AdGroupServiceClient;
import com.google.ads.googleads.v5.services.AssetOperation;
import com.google.ads.googleads.v5.services.AssetServiceClient;
import com.google.ads.googleads.v5.services.CampaignBudgetOperation;
import com.google.ads.googleads.v5.services.CampaignBudgetServiceClient;
import com.google.ads.googleads.v5.services.CampaignOperation;
import com.google.ads.googleads.v5.services.CampaignServiceClient;
import com.google.ads.googleads.v5.services.MutateAdGroupAdsResponse;
import com.google.ads.googleads.v5.services.MutateAdGroupsResponse;
import com.google.ads.googleads.v5.services.MutateAssetsResponse;
import com.google.ads.googleads.v5.services.MutateCampaignBudgetsResponse;
import com.google.ads.googleads.v5.services.MutateCampaignsResponse;
import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteStreams;
import com.google.protobuf.ByteString;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import org.joda.time.DateTime;

/**
 * This example adds a Smart Display campaign, an ad group and a responsive display ad. More
 * information about Smart Display campaigns can be found at
 * https://support.google.com/google-ads/answer/7020281.
 *
 * <p>IMPORTANT: The AssetService requires you to reuse what you've uploaded previously. Therefore,
 * you cannot create multiple image assets with the exact same bytes. In case you want to run this
 * example more than once, note down the created assets' resource names and specify them as
 * command-line arguments for marketing and square marketing images.
 *
 * <p>Alternatively, you can modify the image URLs' constants directly to use other images. You can
 * find image specifications in {@link ResponsiveDisplayAdInfo}.
 */
public class AddSmartDisplayAd {

  // See the descriptions of the 'marketingImages' and 'squareMarketingImages' fields in
  // ResponsiveDisplayAdInfo for specifications of marketing and square marketing images.
  // They can be used to create an image asset for your customer account only once.
  private static final String MARKETING_IMAGE_URL = "https://goo.gl/3b9Wfh";
  private static final String SQUARE_MARKETING_IMAGE_URL = "https://goo.gl/mtt54n";

  private static class AddSmartDisplayAdParams extends CodeSampleParams {

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

    @Parameter(names = ArgumentNames.MARKETING_IMAGE_ASSET_RESOURCE_NAME, required = false)
    private String marketingImageAssetResourceName;

    @Parameter(names = ArgumentNames.SQUARE_MARKETING_IMAGE_ASSET_RESOURCE_NAME, required = false)
    private String squareMarketingImageAssetResourceName;
  }

  public static void main(String[] args) throws IOException {
    AddSmartDisplayAdParams params = new AddSmartDisplayAdParams();
    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");
      // Optional: Specify the resource name of an existing marketing image.
      params.marketingImageAssetResourceName = null;
      // Optional: Specify the resource name of an existing square marketing image.
      params.squareMarketingImageAssetResourceName = null;
    }

    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 AddSmartDisplayAd()
          .runExample(
              googleAdsClient,
              params.customerId,
              params.marketingImageAssetResourceName,
              params.squareMarketingImageAssetResourceName);
    } 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.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param marketingImageAssetResourceName
   * @param squareMarketingImageAssetResourceName
   * @throws GoogleAdsException if an API request failed with one or more service errors.
   */
  private void runExample(
      GoogleAdsClient googleAdsClient,
      long customerId,
      String marketingImageAssetResourceName,
      String squareMarketingImageAssetResourceName)
      throws IOException {
    String budgetResourceName = createCampaignBudget(googleAdsClient, customerId);
    String campaignResourceName =
        createSmartDisplayCampaign(googleAdsClient, customerId, budgetResourceName);
    String adGroupResourceName = createAdGroup(googleAdsClient, customerId, campaignResourceName);
    createResponsiveDisplayAd(
        googleAdsClient,
        customerId,
        adGroupResourceName,
        marketingImageAssetResourceName,
        squareMarketingImageAssetResourceName);
  }

  /**
   * Adds a campaign budget.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @return the campaign budget resource name.
   */
  private static String createCampaignBudget(GoogleAdsClient googleAdsClient, long customerId) {
    // Creates the budget.
    CampaignBudget campaignBudget =
        CampaignBudget.newBuilder()
            .setName("Interplanetary Cruise Budget #" + System.currentTimeMillis())
            .setAmountMicros(5_000_000)
            .setDeliveryMethod(BudgetDeliveryMethod.STANDARD)
            .build();

    // Creates the operation.
    CampaignBudgetOperation operation =
        CampaignBudgetOperation.newBuilder().setCreate(campaignBudget).build();

    // Creates the campaign budget service client.
    try (CampaignBudgetServiceClient campaignBudgetServiceClient =
        googleAdsClient.getLatestVersion().createCampaignBudgetServiceClient()) {
      // Adds the campaign budget.
      MutateCampaignBudgetsResponse response =
          campaignBudgetServiceClient.mutateCampaignBudgets(
              Long.toString(customerId), ImmutableList.of(operation));
      // Displays the result.
      String budgetResourceName = response.getResults(0).getResourceName();
      System.out.printf("Added budget with resource name '%s'.%n", budgetResourceName);
      return budgetResourceName;
    }
  }

  /**
   * Adds a Smart Display campaign.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param budgetResourceName the campaign budget resource name.
   * @return the campaign resource name.
   */
  private static String createSmartDisplayCampaign(
      GoogleAdsClient googleAdsClient, long customerId, String budgetResourceName) {
    // Creates the campaign.
    Campaign campaign =
        Campaign.newBuilder()
            .setName("Smart Display Campaign #" + System.currentTimeMillis())
            // Smart Display campaign requires the advertising channel type as 'DISPLAY'.
            .setAdvertisingChannelType(AdvertisingChannelType.DISPLAY)
            // Smart Display campaign requires the advertising channel sub type as
            // 'DISPLAY_SMART_CAMPAIGN'.
            .setAdvertisingChannelSubType(AdvertisingChannelSubType.DISPLAY_SMART_CAMPAIGN)
            // Smart Display campaign requires the TargetCpa bidding strategy.
            .setTargetCpa(TargetCpa.newBuilder().setTargetCpaMicros(5_000_000).build())
            .setCampaignBudget(budgetResourceName)
            // Optional: Sets the start and end dates for the campaign, beginning one day from
            // now and ending a month from now.
            .setStartDate(new DateTime().plusDays(1).toString("yyyyMMdd"))
            .setEndDate(new DateTime().plusMonths(1).toString("yyyyMMdd"))
            .build();

    // Creates the operation.
    CampaignOperation operation = CampaignOperation.newBuilder().setCreate(campaign).build();

    // Creates the campaign service client.
    try (CampaignServiceClient campaignServiceClient =
        googleAdsClient.getLatestVersion().createCampaignServiceClient()) {
      // Adds the campaign.
      MutateCampaignsResponse response =
          campaignServiceClient.mutateCampaigns(
              Long.toString(customerId), ImmutableList.of(operation));

      String campaignResourceName = response.getResults(0).getResourceName();
      // Displays the results.
      System.out.printf(
          "Added Smart Display campaign with resource name '%s'.%n", campaignResourceName);
      return campaignResourceName;
    }
  }

  /**
   * Adds an ad group.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param campaignResourceName the campaign resource name.
   * @return the ad group resource name.
   */
  private static String createAdGroup(
      GoogleAdsClient googleAdsClient, long customerId, String campaignResourceName) {
    // Creates the ad group.
    AdGroup adGroup =
        AdGroup.newBuilder()
            .setName("Earth to Mars Cruises #" + System.currentTimeMillis())
            .setCampaign(campaignResourceName)
            .setStatus(AdGroupStatus.PAUSED)
            .build();

    // Creates the operation.
    AdGroupOperation operation = AdGroupOperation.newBuilder().setCreate(adGroup).build();

    // Creates the ad group service client.
    try (AdGroupServiceClient adGroupServiceClient =
        googleAdsClient.getLatestVersion().createAdGroupServiceClient()) {
      MutateAdGroupsResponse response =
          adGroupServiceClient.mutateAdGroups(
              Long.toString(customerId), ImmutableList.of(operation));
      String adGroupResourceName = response.getResults(0).getResourceName();
      // Displays the results.
      System.out.printf("Added ad group with resource name '%s'.%n", adGroupResourceName);
      return adGroupResourceName;
    }
  }

  /**
   * Adds a responsive display ad, which is a recommended ad type for Smart Display campaigns.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param adGroupResourceName the ad group resource name.
   * @param marketingImageAssetResourceName optional, the resource name of the marketing image
   *     asset.
   * @param squareMarketingImageAssetResourceName optional, the resource name of the square
   *     marketing image asset.
   */
  private static void createResponsiveDisplayAd(
      GoogleAdsClient googleAdsClient,
      long customerId,
      String adGroupResourceName,
      String marketingImageAssetResourceName,
      String squareMarketingImageAssetResourceName)
      throws IOException {
    // Creates a new image asset for marketing image and square marketing image if there are no
    // asset resource names specified.
    if (marketingImageAssetResourceName == null) {
      marketingImageAssetResourceName =
          createImageAsset(googleAdsClient, customerId, MARKETING_IMAGE_URL, "Marketing Image");
    }
    if (squareMarketingImageAssetResourceName == null) {
      squareMarketingImageAssetResourceName =
          createImageAsset(
              googleAdsClient, customerId, SQUARE_MARKETING_IMAGE_URL, "Square Marketing Image");
    }

    // Creates a responsive display ad info.
    ResponsiveDisplayAdInfo responsiveDisplayAdInfo =
        ResponsiveDisplayAdInfo.newBuilder()
            // Sets some basic required information for the responsive display ad.
            .addHeadlines(AdTextAsset.newBuilder().setText("Travel"))
            .setLongHeadline(AdTextAsset.newBuilder().setText("Travel the World"))
            .addDescriptions(AdTextAsset.newBuilder().setText("Take to the air!"))
            .setBusinessName("Google")
            // Sets the marketing image and square marketing image to the previously created image
            // assets.
            .addMarketingImages(AdImageAsset.newBuilder().setAsset(marketingImageAssetResourceName))
            .addSquareMarketingImages(
                AdImageAsset.newBuilder().setAsset(squareMarketingImageAssetResourceName))
            // Optional: Sets call to action text, price prefix, and promotion text.
            .setCallToActionText("Shop Now")
            .setPricePrefix("as low as")
            .setPromoText("Free shipping!")
            .build();

    // Creates an ad group ad with the created responsive display ad info.
    AdGroupAd adGroupAd =
        AdGroupAd.newBuilder()
            .setAdGroup(adGroupResourceName)
            .setStatus(AdGroupAdStatus.PAUSED)
            .setAd(
                Ad.newBuilder()
                    .addFinalUrls("https://www.example.com")
                    .setResponsiveDisplayAd(responsiveDisplayAdInfo))
            .build();

    // Creates the operation.
    AdGroupAdOperation operation = AdGroupAdOperation.newBuilder().setCreate(adGroupAd).build();

    // Creates the ad group ad service client.
    try (AdGroupAdServiceClient adGroupAdServiceClient =
        googleAdsClient.getLatestVersion().createAdGroupAdServiceClient()) {
      // Adds the responsive display ad.
      MutateAdGroupAdsResponse response =
          adGroupAdServiceClient.mutateAdGroupAds(
              Long.toString(customerId), ImmutableList.of(operation));
      // Displays the response.
      System.out.printf(
          "Added ad group ad with resource name '%s'.%n", response.getResults(0).getResourceName());
    }
  }

  /**
   * Creates an image asset to be used for creating ads.
   *
   * @param googleAdsClient the Google Ads API client.
   * @param customerId the client customer ID.
   * @param imageUrl the image URL to be downloaded.
   * @param imageName the image name.
   * @return the created image asset's resource name.
   */
  private static String createImageAsset(
      GoogleAdsClient googleAdsClient, long customerId, String imageUrl, String imageName)
      throws IOException {
    // Creates a media file.
    byte[] assetBytes = ByteStreams.toByteArray(new URL(imageUrl).openStream());
    Asset asset =
        Asset.newBuilder()
            .setName(imageName)
            .setType(AssetType.IMAGE)
            .setImageAsset(ImageAsset.newBuilder().setData(ByteString.copyFrom(assetBytes)).build())
            .build();

    // Creates an asset operation.
    AssetOperation operation = AssetOperation.newBuilder().setCreate(asset).build();

    // Creates the asset service client.
    try (AssetServiceClient assetServiceClient =
        googleAdsClient.getLatestVersion().createAssetServiceClient()) {
      // Adds the image asset.
      MutateAssetsResponse response =
          assetServiceClient.mutateAssets(Long.toString(customerId), ImmutableList.of(operation));
      String imageResourceName = response.getResults(0).getResourceName();
      System.out.printf("Created image asset with resource name '%s'.%n", imageResourceName);
      return imageResourceName;
    }
  }
}

C#

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

using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.Util;
using Google.Ads.GoogleAds.V5.Common;
using Google.Ads.GoogleAds.V5.Enums;
using Google.Ads.GoogleAds.V5.Errors;
using Google.Ads.GoogleAds.V5.Resources;
using Google.Ads.GoogleAds.V5.Services;
using Google.Protobuf;
using System;
using System.Linq;
using static Google.Ads.GoogleAds.V5.Enums.AdGroupAdStatusEnum.Types;
using static Google.Ads.GoogleAds.V5.Enums.AdvertisingChannelSubTypeEnum.Types;
using static Google.Ads.GoogleAds.V5.Enums.AdvertisingChannelTypeEnum.Types;
using static Google.Ads.GoogleAds.V5.Enums.AssetTypeEnum.Types;
using static Google.Ads.GoogleAds.V5.Enums.BudgetDeliveryMethodEnum.Types;
using static Google.Ads.GoogleAds.V5.Enums.CampaignStatusEnum.Types;
using static Google.Ads.GoogleAds.V5.Enums.MimeTypeEnum.Types;

namespace Google.Ads.GoogleAds.Examples.V5
{
    /// <summary>
    ///
    /// This code example adds a Smart Display campaign, an ad group and a responsive display ad.
    /// More information about Smart Display campaigns can be found at
    /// https://support.google.com/google-ads/answer/7020281.
    /// </summary>
    public class AddSmartDisplayAd : ExampleBase
    {
        private const string MARKETING_IMAGE_URL = "https://goo.gl/3b9Wfh";
        private const int MARKETING_IMAGE_WIDTH = 600;
        private const int MARKETING_IMAGE_HEIGHT = 315;

        private const string SQUARE_MARKETING_IMAGE_URL = "https://goo.gl/mtt54n";
        private const int SQUARE_MARKETING_IMAGE_SIZE = 512;

        /// <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)
        {
            AddSmartDisplayAd codeExample = new AddSmartDisplayAd();
            Console.WriteLine(codeExample.Description);

            // The Google Ads customer ID for which the call is made.
            long customerId = long.Parse("INSERT_CUSTOMER_ID_HERE");

            codeExample.Run(new GoogleAdsClient(), customerId);
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description =>
            "This code example adds a Smart Display campaign, an ad group and a responsive " +
            "display ad. More information about Smart Display campaigns can be found at " +
            "https://support.google.com/google-ads/answer/7020281.";

        /// <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 call is made.</param>
        public void Run(GoogleAdsClient client, long customerId)
        {
            try
            {
                string budgetResourceName = CreateBudget(client, customerId);
                string campaignResourceName = CreateSmartDisplayCampaign(client, customerId,
                    budgetResourceName);
                string adGroupResourceName = CreateAdGroup(client, customerId,
                    campaignResourceName);
                string marketingImageAssetResourceName = UploadImageAsset(client, customerId,
                    MARKETING_IMAGE_URL, MARKETING_IMAGE_WIDTH, MARKETING_IMAGE_HEIGHT);
                string squareMarketingImageAssetResourceName = UploadImageAsset(client, customerId,
                    SQUARE_MARKETING_IMAGE_URL, SQUARE_MARKETING_IMAGE_SIZE,
                    SQUARE_MARKETING_IMAGE_SIZE);
                CreateResponsiveDisplayAd(client, customerId, adGroupResourceName,
                    marketingImageAssetResourceName, squareMarketingImageAssetResourceName);
            }
            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 the budget for the campaign.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <returns>The resource name of the newly created campaign budget.</returns>
        private static string CreateBudget(GoogleAdsClient client, long customerId)
        {
            // Get the BudgetService.
            CampaignBudgetServiceClient budgetService = client.GetService(
                Services.V5.CampaignBudgetService);

            // Create the campaign budget.
            CampaignBudget budget = new CampaignBudget()
            {
                Name = "Interplanetary Cruise Budget #" + ExampleUtilities.GetRandomString(),
                DeliveryMethod = BudgetDeliveryMethod.Standard,
                AmountMicros = 500000
            };

            // Create the operation.
            CampaignBudgetOperation budgetOperation = new CampaignBudgetOperation()
            {
                Create = budget
            };

            // Create the campaign budget.
            MutateCampaignBudgetsResponse response = budgetService.MutateCampaignBudgets(
                customerId.ToString(), new CampaignBudgetOperation[] { budgetOperation });

            string budgetResourceName = response.Results.First().ResourceName;

            // Print out some information about the added budget.
            Console.WriteLine($"Added campaign budget with resource name = '{budgetResourceName}'.");

            return budgetResourceName;
        }

        /// <summary>
        /// Creates the smart display campaign.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="budgetResourceName">The campaign budget resource name.</param>
        /// <returns>Resource name of the newly created campaign.</returns>
        private string CreateSmartDisplayCampaign(GoogleAdsClient client, long customerId,
            string budgetResourceName)
        {
            // Get the CampaignService.
            CampaignServiceClient campaignService = client.GetService(Services.V5.CampaignService);

            // Create the campaign.
            Campaign campaign = new Campaign()
            {
                Name = "Smart Display Campaign #" + ExampleUtilities.GetRandomString(),

                // Smart Display campaign requires the advertising_channel_type as 'DISPLAY'.
                AdvertisingChannelType = AdvertisingChannelType.Display,

                // Smart Display campaign requires the advertising_channel_sub_type as
                // 'DISPLAY_SMART_CAMPAIGN'.
                AdvertisingChannelSubType = AdvertisingChannelSubType.DisplaySmartCampaign,

                // Recommendation: Set the campaign to PAUSED when creating it to prevent
                // the ads from immediately serving. Set to ENABLED once you've added
                // targeting and the ads are ready to serve
                Status = CampaignStatus.Paused,

                // Smart Display campaign requires the TargetCpa bidding strategy.
                TargetCpa = new TargetCpa() { TargetCpaMicros = 5000000 },

                CampaignBudget = budgetResourceName,

                // Optional: Set the start date.
                StartDate = DateTime.Now.AddDays(1).ToString("yyyyMMdd"),

                // Optional: Set the end date.
                EndDate = DateTime.Now.AddYears(1).ToString("yyyyMMdd"),
            };

            // Create the operation.
            CampaignOperation operation = new CampaignOperation() { Create = campaign };

            // Add the campaign.
            MutateCampaignsResponse response = campaignService.MutateCampaigns(
                customerId.ToString(), new[] { operation });

            string campaignResourceName = response.Results.First().ResourceName;

            // Print out some information about the added campaign.
            Console.WriteLine($"Added campaign with resource name = '{campaignResourceName}'.");

            return campaignResourceName;
        }

        /// <summary>
        /// Creates the ad group.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="campaignResourceName">The campaign resource name.</param>
        /// <returns>The resource name of the newly created ad group.</returns>
        private string CreateAdGroup(GoogleAdsClient client, long customerId,
            string campaignResourceName)
        {
            // Get the AdGroupService.
            AdGroupServiceClient adGroupService = client.GetService(Services.V5.AdGroupService);

            // Create the ad group.
            AdGroup adGroup = new AdGroup()
            {
                Name = $"Earth to Mars Cruises #{ExampleUtilities.GetRandomString()}",
                Status = AdGroupStatusEnum.Types.AdGroupStatus.Enabled,
                Campaign = campaignResourceName,
            };

            // Create the operation.
            AdGroupOperation operation = new AdGroupOperation()
            {
                Create = adGroup
            };

            // Create the ad groups.
            MutateAdGroupsResponse response = adGroupService.MutateAdGroups(
                customerId.ToString(), new[] { operation });

            string adGroupResourceName = response.Results.First().ResourceName;

            // Print out some information about the added ad group.
            Console.WriteLine($"Added ad group with resource name = '{adGroupResourceName}'.");

            return adGroupResourceName;
        }

        /// <summary>
        /// Uploads the image asset.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="imageUrl">The image URL.</param>
        /// <param name="width">The image width in pixels.</param>
        /// <param name="height">The image height in pixels.</param>
        /// <returns></returns>
        private static string UploadImageAsset(GoogleAdsClient client, long customerId,
            string imageUrl, long width, long height)
        {
            // Get the AssetServiceClient.
            AssetServiceClient assetService =
                client.GetService(Services.V5.AssetService);

            // Creates an image content.
            byte[] imageContent = MediaUtilities.GetAssetDataFromUrl(imageUrl, client.Config);

            // Creates an image asset.
            ImageAsset imageAsset = new ImageAsset()
            {
                Data = ByteString.CopyFrom(imageContent),
                FileSize = imageContent.Length,
                MimeType = MimeType.ImageJpeg,
                FullSize = new ImageDimension()
                {
                    HeightPixels = height,
                    WidthPixels = width,
                    Url = imageUrl
                }
            };

            // Creates an asset.
            Asset asset = new Asset()
            {
                // Optional: Provide a unique friendly name to identify your asset.
                // If you specify the name field, then both the asset name and the image being
                // uploaded should be unique, and should not match another ACTIVE asset in this
                // customer account.
                // Name = 'Jupiter Trip #' + ExampleUtilities.GetRandomString(),
                Type = AssetType.Image,
                ImageAsset = imageAsset
            };

            // Creates an asset operation.
            AssetOperation operation = new AssetOperation()
            {
                Create = asset
            };

            // Issues a mutate request to add the asset.
            MutateAssetsResponse response =
                assetService.MutateAssets(customerId.ToString(), new[] { operation });

            string assetResourceName = response.Results.First().ResourceName;

            // Print out some information about the added asset.
            Console.WriteLine($"Added asset with resource name = '{assetResourceName}'.");

            return assetResourceName;
        }

        /// <summary>
        /// Creates the responsive display ad.
        /// </summary>
        /// <param name="client">The Google Ads client.</param>
        /// <param name="customerId">The Google Ads customer ID for which the call is made.</param>
        /// <param name="adGroupResourceName">The ad group resource name.</param>
        /// <param name="marketingImageAssetResourceName">The marketing image asset resource
        /// name.</param>
        /// <param name="squareMarketingImageAssetResourceName">The square marketing image asset
        /// resource name.</param>
        /// <returns>Resource name of the newly created ad.</returns>
        private static string CreateResponsiveDisplayAd(GoogleAdsClient client, long customerId,
            string adGroupResourceName, string marketingImageAssetResourceName,
            string squareMarketingImageAssetResourceName)
        {
            // Get the AdGroupAdServiceClient.
            AdGroupAdServiceClient adGroupAdService =
                client.GetService(Services.V5.AdGroupAdService);

            // Creates a responsive display ad info.
            ResponsiveDisplayAdInfo responsiveDisplayAdInfo = new ResponsiveDisplayAdInfo()
            {
                // Sets some basic required information for the responsive display ad.
                Headlines = { new AdTextAsset() { Text = "Travel" } },
                LongHeadline = new AdTextAsset() { Text = "Travel the World" },
                Descriptions = { new AdTextAsset() { Text = "Take to the air!" } },
                BusinessName = "Google",

                // Sets the marketing image and square marketing image to the previously created
                // image assets.
                MarketingImages =
                {
                    new AdImageAsset() { Asset = marketingImageAssetResourceName }
                },
                SquareMarketingImages =
                {
                    new AdImageAsset() { Asset = squareMarketingImageAssetResourceName }
                },

                // Optional: Sets call to action text, price prefix and promotion text.
                CallToActionText = "Shop Now",
                PricePrefix = "as low as",
                PromoText = "Free shipping!"
            };

            // Creates an ad group ad with the created responsive display ad info.
            AdGroupAd adGroupAd = new AdGroupAd()
            {
                AdGroup = adGroupResourceName,
                Status = AdGroupAdStatus.Paused,
                Ad = new Ad()
                {
                    FinalUrls = { "https://www.example.com" },
                    ResponsiveDisplayAd = responsiveDisplayAdInfo
                }
            };

            // Creates an ad group ad operation.
            AdGroupAdOperation operation = new AdGroupAdOperation()
            {
                Create = adGroupAd
            };

            // Issues a mutate request to add the ad.
            MutateAdGroupAdsResponse response =
                adGroupAdService.MutateAdGroupAds(customerId.ToString(), new[] { operation });

            string adGroupAdResourceName = response.Results.First().ResourceName;

            // Print out some information about the added ad group ad.
            Console.WriteLine($"Added ad group ad with resource name = '{adGroupAdResourceName}'.");

            return adGroupAdResourceName;
        }
    }
}

PHP

<?php

/**
 * Copyright 2019 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\AdvancedOperations;

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\Lib\OAuth2TokenBuilder;
use Google\Ads\GoogleAds\Lib\V5\GoogleAdsClient;
use Google\Ads\GoogleAds\Lib\V5\GoogleAdsClientBuilder;
use Google\Ads\GoogleAds\Lib\V5\GoogleAdsException;
use Google\Ads\GoogleAds\V5\Common\AdImageAsset;
use Google\Ads\GoogleAds\V5\Common\AdTextAsset;
use Google\Ads\GoogleAds\V5\Common\ImageAsset;
use Google\Ads\GoogleAds\V5\Common\ResponsiveDisplayAdInfo;
use Google\Ads\GoogleAds\V5\Common\TargetCpa;
use Google\Ads\GoogleAds\V5\Enums\AdGroupAdStatusEnum\AdGroupAdStatus;
use Google\Ads\GoogleAds\V5\Enums\AdGroupStatusEnum\AdGroupStatus;
use Google\Ads\GoogleAds\V5\Enums\AdvertisingChannelSubTypeEnum\AdvertisingChannelSubType;
use Google\Ads\GoogleAds\V5\Enums\AdvertisingChannelTypeEnum\AdvertisingChannelType;
use Google\Ads\GoogleAds\V5\Enums\AssetTypeEnum\AssetType;
use Google\Ads\GoogleAds\V5\Enums\BudgetDeliveryMethodEnum\BudgetDeliveryMethod;
use Google\Ads\GoogleAds\V5\Errors\GoogleAdsError;
use Google\Ads\GoogleAds\V5\Resources\Ad;
use Google\Ads\GoogleAds\V5\Resources\AdGroup;
use Google\Ads\GoogleAds\V5\Resources\AdGroupAd;
use Google\Ads\GoogleAds\V5\Resources\Asset;
use Google\Ads\GoogleAds\V5\Resources\Campaign;
use Google\Ads\GoogleAds\V5\Resources\CampaignBudget;
use Google\Ads\GoogleAds\V5\Services\AdGroupAdOperation;
use Google\Ads\GoogleAds\V5\Services\AdGroupOperation;
use Google\Ads\GoogleAds\V5\Services\AssetOperation;
use Google\Ads\GoogleAds\V5\Services\CampaignBudgetOperation;
use Google\Ads\GoogleAds\V5\Services\CampaignOperation;
use Google\Ads\GoogleAds\V5\Services\MutateAdGroupAdsResponse;
use Google\Ads\GoogleAds\V5\Services\MutateAdGroupsResponse;
use Google\Ads\GoogleAds\V5\Services\MutateCampaignBudgetsResponse;
use Google\Ads\GoogleAds\V5\Services\MutateCampaignsResponse;
use Google\ApiCore\ApiException;

/**
 * This example adds a Smart Display campaign, an ad group and a responsive display ad.
 * More information about Smart Display campaigns can be found at
 * https://support.google.com/google-ads/answer/7020281.
 *
 * IMPORTANT: The AssetService requires you to reuse what you've uploaded previously. Therefore,
 * you cannot create an image asset with the exactly same bytes. In case you want to run this
 * example more than once, note down the created assets' IDs and specify them as
 * command-line arguments for marketing and square marketing images.
 *
 * Alternatively, you can modify the image URLs' constants directly to use other images. You can
 * find image specifications in the ResponsiveDisplayAdInfo.php file.
 */
class AddSmartDisplayAd
{
    private const CUSTOMER_ID = 'INSERT_CUSTOMER_ID_HERE';
    // See the descriptions of the 'marketing_images' and 'square_marketing_images' fields in
    // ResponsiveDisplayAdInfo.php for specifications of marketing and square marketing images.
    // They can be used to create an image asset for your customer account only once.
    private const MARKETING_IMAGE_URL = 'https://goo.gl/3b9Wfh';
    private const SQUARE_MARKETING_IMAGE_URL = 'https://goo.gl/mtt54n';

    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,
            ArgumentNames::MARKETING_IMAGE_ASSET_ID => GetOpt::OPTIONAL_ARGUMENT,
            ArgumentNames::SQUARE_MARKETING_IMAGE_ASSET_ID => GetOpt::OPTIONAL_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,
                $options[ArgumentNames::MARKETING_IMAGE_ASSET_ID],
                $options[ArgumentNames::SQUARE_MARKETING_IMAGE_ASSET_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
     * @param int|null $marketingImageAssetId optional, the ID of marketing image asset
     * @param int|null $squareMarketingImageAssetId optional, the ID of square marketing image asset
     */
    public static function runExample(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        ?int $marketingImageAssetId,
        ?int $squareMarketingImageAssetId
    ) {
        $budgetResourceName = self::createCampaignBudget($googleAdsClient, $customerId);
        $campaignResourceName = self::createSmartDisplayCampaign(
            $googleAdsClient,
            $customerId,
            $budgetResourceName
        );
        $adGroupResourceName = self::createAdGroup(
            $googleAdsClient,
            $customerId,
            $campaignResourceName
        );
        self::createResponsiveDisplayAd(
            $googleAdsClient,
            $customerId,
            $adGroupResourceName,
            $marketingImageAssetId,
            $squareMarketingImageAssetId
        );
    }

    /**
     * Creates a campaign budget.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @return string the resource name of newly created campaign budget
     */
    private static function createCampaignBudget(
        GoogleAdsClient $googleAdsClient,
        int $customerId
    ) {
        // Creates a campaign budget.
        $campaignBudget = new CampaignBudget([
            'name' => 'Interplanetary Cruise Budget #' . uniqid(),
            'delivery_method' => BudgetDeliveryMethod::STANDARD,
            'amount_micros' => 5000000
        ]);

        // Creates a campaign budget operation.
        $campaignBudgetOperation = new CampaignBudgetOperation();
        $campaignBudgetOperation->setCreate($campaignBudget);

        // Issues a mutate request to add campaign budgets.
        $campaignBudgetServiceClient = $googleAdsClient->getCampaignBudgetServiceClient();
        /** @var MutateCampaignBudgetsResponse $campaignBudgetResponse */
        $campaignBudgetResponse = $campaignBudgetServiceClient->mutateCampaignBudgets(
            $customerId,
            [$campaignBudgetOperation]
        );

        // Prints out some information about the created campaign budget.
        $campaignBudgetResourceName = $campaignBudgetResponse->getResults()[0]->getResourceName();
        printf("Added budget named '%s'.%s", $campaignBudgetResourceName, PHP_EOL);

        return $campaignBudgetResourceName;
    }

    /**
     * Creates a Smart Display campaign.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $campaignBudgetResourceName the resource name of the campaign budget
     * @return string the resource name of the newly created campaign
     */
    private static function createSmartDisplayCampaign(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $campaignBudgetResourceName
    ) {
        $campaign = new Campaign([
            'name' => 'Smart Display Campaign #' . uniqid(),
            // Smart Display campaign requires the advertising_channel_type as 'DISPLAY'.
            'advertising_channel_type' => AdvertisingChannelType::DISPLAY,
            // Smart Display campaign requires the advertising_channel_sub_type as
            // 'DISPLAY_SMART_CAMPAIGN'.
            'advertising_channel_sub_type' => AdvertisingChannelSubType::DISPLAY_SMART_CAMPAIGN,
            // Smart Display campaign requires the TargetCpa bidding strategy.
            'target_cpa' => new TargetCpa(['target_cpa_micros' => 5000000]),
            'campaign_budget' => $campaignBudgetResourceName,
            // Optional: Sets the start and end dates for the campaign, beginning one day from
            // now and ending a month from now.
            'start_date' => date('Ymd', strtotime('+1 day')),
            'end_date' => date('Ymd', strtotime('+1 month'))
        ]);

        // Creates a campaign operation.
        $campaignOperation = new CampaignOperation();
        $campaignOperation->setCreate($campaign);

        // Issues a mutate request to add the campaign.
        $campaignServiceClient = $googleAdsClient->getCampaignServiceClient();
        /** @var MutateCampaignsResponse $campaignResponse */
        $campaignResponse = $campaignServiceClient->mutateCampaigns(
            $customerId,
            [$campaignOperation]
        );

        $campaignResourceName = $campaignResponse->getResults()[0]->getResourceName();
        printf("Added a Smart Display campaign named '%s'.%s", $campaignResourceName, PHP_EOL);

        return $campaignResourceName;
    }

    /**
     * Creates an ad group.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $campaignResourceName the resource name of the campaign
     * @return string the resource name of the newly created ad group
     */
    private static function createAdGroup(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $campaignResourceName
    ) {
        // Constructs an ad group and set its type.
        $adGroup = new AdGroup([
            'name' => 'Earth to Mars Cruises #' . uniqid(),
            'campaign' => $campaignResourceName,
            'status' => AdGroupStatus::PAUSED,
        ]);

        // Creates an ad group operation.
        $adGroupOperation = new AdGroupOperation();
        $adGroupOperation->setCreate($adGroup);

        // Issues a mutate request to add the ad group.
        $adGroupServiceClient = $googleAdsClient->getAdGroupServiceClient();
        /** @var MutateAdGroupsResponse $adGroupResponse */
        $adGroupResponse = $adGroupServiceClient->mutateAdGroups($customerId, [$adGroupOperation]);

        // Print out some information about the added ad group.
        $adGroupResourceName = $adGroupResponse->getResults()[0]->getResourceName();
        printf("Added ad group named '%s'.%s", $adGroupResourceName, PHP_EOL);

        return $adGroupResourceName;
    }

    /**
     * Creates a responsive display ad, which is a recommended ad type for Smart Display campaigns.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $adGroupResourceName the ad group resource name
     * @param int|null $marketingImageAssetId optional, the ID of marketing image asset
     * @param int|null $squareMarketingImageAssetId optional, the ID of square marketing image asset
     */
    private static function createResponsiveDisplayAd(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $adGroupResourceName,
        ?int $marketingImageAssetId,
        ?int $squareMarketingImageAssetId
    ) {
        // Creates a new image asset for marketing image and square marketing image if there are no
        // assets' IDs specified.
        $marketingImageAssetResourceName = $marketingImageAssetId
            ? ResourceNames::forAsset($customerId, $marketingImageAssetId)
            : self::createImageAsset(
                $googleAdsClient,
                $customerId,
                self::MARKETING_IMAGE_URL,
                'Marketing Image'
            );
        $squareMarketingImageAssetResourceName = $squareMarketingImageAssetId
            ? ResourceNames::forAsset($customerId, $squareMarketingImageAssetId)
            : self::createImageAsset(
                $googleAdsClient,
                $customerId,
                self::SQUARE_MARKETING_IMAGE_URL,
                'Square Marketing Image'
            );

        // Creates a responsive display ad info.
        $responsiveDisplayAdInfo = new ResponsiveDisplayAdInfo([
            // Sets some basic required information for the responsive display ad.
            'headlines' => [new AdTextAsset(['text' => 'Travel'])],
            'long_headline' => new AdTextAsset(['text' => 'Travel the World']),
            'descriptions' => [new AdTextAsset(['text' => 'Take to the air!'])],
            'business_name' => 'Google',
            // Sets the marketing image and square marketing image to the previously created
            // image assets.
            'marketing_images' => [
                new AdImageAsset(['asset' => $marketingImageAssetResourceName])
            ],
            'square_marketing_images' => [
                new AdImageAsset(['asset' => $squareMarketingImageAssetResourceName])
            ],
            // Optional: Sets call to action text, price prefix and promotion text.
            'call_to_action_text' => 'Shop Now',
            'price_prefix' => 'as low as',
            'promo_text' => 'Free shipping!',
        ]);

        // Creates an ad group ad with the created responsive display ad info.
        $adGroupAd = new AdGroupAd([
            'ad_group' => $adGroupResourceName,
            'status' => AdGroupAdStatus::PAUSED,
            'ad' => new Ad([
                'final_urls' => ['https://www.example.com'],
                'responsive_display_ad' => $responsiveDisplayAdInfo
            ])
        ]);

        // Creates an ad group ad operation.
        $adGroupAdOperation = new AdGroupAdOperation();
        $adGroupAdOperation->setCreate($adGroupAd);

        // Issues a mutate request to add the ad group ad.
        $adGroupAdServiceClient = $googleAdsClient->getAdGroupAdServiceClient();
        /** @var MutateAdGroupAdsResponse $adGroupAdResponse */
        $adGroupAdResponse = $adGroupAdServiceClient->mutateAdGroupAds(
            $customerId,
            [$adGroupAdOperation]
        );

        // Prints out some information about the newly created ad.
        $adGroupAdResourceName = $adGroupAdResponse->getResults()[0]->getResourceName();
        printf("Added ad group ad named '%s'.%s", $adGroupAdResourceName, PHP_EOL);
    }

    /**
     * Creates an image asset to be used for creating ads.
     *
     * @param GoogleAdsClient $googleAdsClient the Google Ads API client
     * @param int $customerId the customer ID
     * @param string $imageUrl the image URL to be downloaded
     * @param string $imageName the image name
     * @return string the created image asset's resource name
     */
    private static function createImageAsset(
        GoogleAdsClient $googleAdsClient,
        int $customerId,
        string $imageUrl,
        string $imageName
    ) {
        // Creates a media file.
        $asset = new Asset([
            'name' => $imageName,
            'type' => AssetType::IMAGE,
            'image_asset' => new ImageAsset(['data' => file_get_contents($imageUrl)])
        ]);

        // Creates an asset operation.
        $assetOperation = new AssetOperation();
        $assetOperation->setCreate($asset);

        // Issues a mutate request to add the asset.
        $assetServiceClient = $googleAdsClient->getAssetServiceClient();
        $response = $assetServiceClient->mutateAssets($customerId, [$assetOperation]);

        // Prints out information about the newly added asset.
        $assetResourceName = $response->getResults()[0]->getResourceName();
        printf(
            "A new image asset has been added with resource name: '%s'.%s",
            $assetResourceName,
            PHP_EOL
        );

        return $assetResourceName;
    }
}

AddSmartDisplayAd::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 adds a smart display campaign, an ad group, and a responsive display ad.

More information about Smart Display campaigns can be found at:
https://support.google.com/google-ads/answer/7020281

IMPORTANT: The AssetService requires you to reuse what you've uploaded
previously. Therefore, you cannot create an image asset with the exactly same
bytes. In case you want to run this example more than once, note down the
created assets' resource names and specify them as command-line arguments for
marketing and square marketing images.

Alternatively, you can modify the image URLs' constants directly to use other
images. You can find image specifications in the pydoc for
ResponsiveDisplayAdInfo in common/ad_type_infos_pb2.py.
"""


import argparse
import datetime
import requests
import sys
from uuid import uuid4

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


_DATE_FORMAT = "%Y%m%d"
_MARKETING_IMAGE_URL = "https://goo.gl/3b9Wfh"
_MARKETING_IMAGE_WIDTH = 600
_MARKETING_IMAGE_HEIGHT = 315
_SQUARE_MARKETING_IMAGE_URL = "https://goo.gl/mtt54n"
_SQUARE_MARKETING_IMAGE_SIZE = 512


def main(
    client,
    customer_id,
    marketing_image_asset_id=None,
    square_marketing_image_asset_id=None,
):
    budget_resource_name = _create_budget(client, customer_id)
    print(f'Created budget with resource name "{budget_resource_name}".')

    campaign_resource_name = _create_smart_display_campaign(
        client, customer_id, budget_resource_name
    )
    print(
        "Created smart display campaign with resource name "
        f'"{campaign_resource_name}".'
    )

    ad_group_resource_name = _create_ad_group(
        client, customer_id, campaign_resource_name
    )
    print(f'Created ad group with resource name "{ad_group_resource_name}"')

    if marketing_image_asset_id:
        print(
            "Using existing marketing image asset with resource name "
            f'"{marketing_image_asset_id}".'
        )
    else:
        marketing_image_asset_id = _upload_image_asset(
            client,
            customer_id,
            _MARKETING_IMAGE_URL,
            _MARKETING_IMAGE_WIDTH,
            _MARKETING_IMAGE_HEIGHT,
        )
        print(
            "Created marketing image asset with resource name "
            f'"{marketing_image_asset_id}".'
        )

    if square_marketing_image_asset_id:
        print(
            "Using existing square marketing image asset with resource name "
            f'"{square_marketing_image_asset_id}".'
        )
    else:
        square_marketing_image_asset_id = _upload_image_asset(
            client,
            customer_id,
            _SQUARE_MARKETING_IMAGE_URL,
            _SQUARE_MARKETING_IMAGE_SIZE,
            _SQUARE_MARKETING_IMAGE_SIZE,
        )
        print(
            "Created square marketing image asset with resource name "
            f'"{square_marketing_image_asset_id}".'
        )

    responsive_display_ad_resource_name = _create_responsive_display_ad(
        client,
        customer_id,
        ad_group_resource_name,
        marketing_image_asset_id,
        square_marketing_image_asset_id,
    )

    print(
        "Created responsive display ad with resource name "
        f'"{responsive_display_ad_resource_name}".'
    )


def _create_budget(client, customer_id):
    campaign_budget_operation = client.get_type(
        "CampaignBudgetOperation", version="v5"
    )
    campaign_budget = campaign_budget_operation.create
    campaign_budget.name = f"Interplanetary Cruise Budget #{uuid4()}"
    campaign_budget.delivery_method = client.get_type(
        "BudgetDeliveryMethodEnum"
    ).STANDARD
    campaign_budget.amount_micros = 500000

    campaign_budget_service = client.get_service(
        "CampaignBudgetService", version="v5"
    )

    try:
        campaign_budget_response = campaign_budget_service.mutate_campaign_budgets(
            customer_id, [campaign_budget_operation]
        )
        return campaign_budget_response.results[0].resource_name
    except GoogleAdsException as ex:
        _handle_google_ads_exception(ex)


def _create_smart_display_campaign(client, customer_id, budget_resource_name):
    campaign_operation = client.get_type("CampaignOperation", version="v5")
    campaign = campaign_operation.create
    campaign.name = f"Smart Display Campaign #{uuid4()}"
    advertising_channel_type_enum = client.get_type(
        "AdvertisingChannelTypeEnum", version="v5"
    )
    campaign.advertising_channel_type = advertising_channel_type_enum.DISPLAY
    advertising_channel_sub_type_enum = client.get_type(
        "AdvertisingChannelSubTypeEnum", version="v5"
    )
    # Smart Display campaign requires the advertising_channel_sub_type as
    # "DISPLAY_SMART_CAMPAIGN".
    campaign.advertising_channel_sub_type = (
        advertising_channel_sub_type_enum.DISPLAY_SMART_CAMPAIGN
    )
    campaign_status_enum = client.get_type("CampaignStatusEnum", version="v5")
    campaign.status = campaign_status_enum.PAUSED
    # Smart Display campaign requires the TargetCpa bidding strategy.
    campaign.target_cpa.target_cpa_micros = 5000000
    campaign.campaign_budget = budget_resource_name
    # Optional: Set the start and end date.
    start_date = datetime.date.today() + datetime.timedelta(days=1)
    campaign.start_date = start_date.strftime(_DATE_FORMAT)
    end_date = start_date + datetime.timedelta(days=365)
    campaign.end_date = end_date.strftime(_DATE_FORMAT)

    campaign_service = client.get_service("CampaignService", version="v5")

    try:
        campaign_response = campaign_service.mutate_campaigns(
            customer_id, [campaign_operation]
        )
        return campaign_response.results[0].resource_name
    except GoogleAdsException as ex:
        _handle_google_ads_exception(ex)


def _create_ad_group(client, customer_id, campaign_resource_name):
    ad_group_operation = client.get_type("AdGroupOperation", version="v5")
    ad_group = ad_group_operation.create
    ad_group.name = f"Earth to Mars Cruises #{uuid4()}"
    ad_group_status_enum = client.get_type("AdGroupStatusEnum", version="v5")
    ad_group.status = ad_group_status_enum.PAUSED
    ad_group.campaign = campaign_resource_name

    ad_group_service = client.get_service("AdGroupService", version="v5")

    try:
        ad_group_response = ad_group_service.mutate_ad_groups(
            customer_id, [ad_group_operation]
        )
        return ad_group_response.results[0].resource_name
    except GoogleAdsException as ex:
        _handle_google_ads_exception(ex)


def _upload_image_asset(
    client, customer_id, image_url, image_width, image_height
):
    # Download image from URL
    image_content = requests.get(image_url).content

    asset_operation = client.get_type("AssetOperation", version="v5")
    asset = asset_operation.create
    # Optional: Provide a unique friendly name to identify your asset. If you
    # specify the name field, then both the asset name and the image being
    # uploaded should be unique, and should not match another ACTIVE asset in
    # this customer account.
    # asset.name = f'Jupiter Trip #{uuid4()}'
    asset_type_enum = client.get_type("AssetTypeEnum", version="v5")
    asset.type = asset_type_enum.IMAGE
    image_asset = asset.image_asset
    image_asset.data = image_content
    image_asset.file_size = len(image_content)
    image_asset.mime_type = client.get_type("MimeTypeEnum").IMAGE_JPEG
    image_asset.full_size.width_pixels = image_width
    image_asset.full_size.height_pixels = image_height
    image_asset.full_size.url = image_url

    asset_service = client.get_service("AssetService", version="v5")
    content_type_enum = client.get_type("ResponseContentTypeEnum", version="v5")

    try:
        mutate_asset_response = asset_service.mutate_assets(
            customer_id,
            [asset_operation],
            # Setting this parameter tells the API to return the Asset
            # object in the response, allowing us to easily retrieve
            # its ID.
            response_content_type=content_type_enum.MUTABLE_RESOURCE,
        )
        return mutate_asset_response.results[0].asset.id
    except GoogleAdsException as ex:
        _handle_google_ads_exception(ex)


def _create_responsive_display_ad(
    client,
    customer_id,
    ad_group_resource_name,
    marketing_image_asset_id,
    square_marketing_image_asset_id,
):
    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_resource_name
    ad_group_ad.status = client.get_type(
        "AdGroupAdStatusEnum", version="v5"
    ).PAUSED
    ad = ad_group_ad.ad
    ad.final_urls.append("https://www.example.com")
    responsive_display_ad = ad.responsive_display_ad
    headline = responsive_display_ad.headlines.add()
    headline.text = "Travel"
    responsive_display_ad.long_headline.text = "Travel the World"
    description = responsive_display_ad.descriptions.add()
    description.text = "Take to the air!"
    responsive_display_ad.business_name = "Google"

    asset_service = client.get_service("AssetService", version="v5")
    marketing_image = responsive_display_ad.marketing_images.add()
    marketing_image.asset = asset_service.asset_path(
        customer_id, marketing_image_asset_id
    )
    square_marketing_image = responsive_display_ad.square_marketing_images.add()
    square_marketing_image.asset = asset_service.asset_path(
        customer_id, square_marketing_image_asset_id
    )
    responsive_display_ad.call_to_action_text = "Shop Now"
    responsive_display_ad.price_prefix = "as low as"
    responsive_display_ad.promo_text = "Free shipping!"

    ad_group_ad_service = client.get_service("AdGroupAdService", version="v5")

    try:
        ad_group_ad_response = ad_group_ad_service.mutate_ad_group_ads(
            customer_id, [ad_group_ad_operation]
        )
    except GoogleAdsException as ex:
        _handle_google_ads_exception(ex)


def _handle_google_ads_exception(exception):
    """Prints the details of a GoogleAdsException object.

    Args:
        exception: an instance of GoogleAdsException.
    """
    print(
        f'Request with ID "{exception.request_id}" failed with status '
        f'"{exception.error.code().name}" and includes the following errors:'
    )
    for error in exception.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)


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

    parser = argparse.ArgumentParser(
        description=(
            "Creates a Smart Display campaign, and an ad group that "
            "are then used to create a responsive display ad."
        )
    )
    # 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(
        "-m",
        "--marketing_image_asset_id",
        type=str,
        required=False,
        help=("The ID for an image asset to be used as a marketing image."),
    )
    parser.add_argument(
        "-s",
        "--square_marketing_image_asset_id",
        type=str,
        required=False,
        help=(
            "The resource name for an image asset to be used as a square "
            "marketing image."
        ),
    )
    args = parser.parse_args()

    main(
        google_ads_client,
        args.customer_id,
        args.marketing_image_asset_id,
        args.square_marketing_image_asset_id,
    )

Perl

#!/usr/bin/perl -w
#
# Copyright 2019, 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 adds a Smart Display campaign, an ad group and a responsive display
# ad. More information about Smart Display campaigns can be found at
# https://support.google.com/google-ads/answer/7020281.
#
# IMPORTANT: The AssetService requires you to reuse what you've uploaded previously.
# Therefore, you cannot create an image asset with the exactly same bytes. In
# case you want to run this example more than once, note down the created assets'
# IDs and specify them as command-line arguments for marketing and square marketing
# images.
#
# Alternatively, you can modify the image URLs' constants directly to use other
# images.

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::Utils::MediaUtils;
use Google::Ads::GoogleAds::V5::Resources::CampaignBudget;
use Google::Ads::GoogleAds::V5::Resources::Campaign;
use Google::Ads::GoogleAds::V5::Resources::AdGroup;
use Google::Ads::GoogleAds::V5::Resources::AdGroupAd;
use Google::Ads::GoogleAds::V5::Resources::Ad;
use Google::Ads::GoogleAds::V5::Resources::Asset;
use Google::Ads::GoogleAds::V5::Common::TargetCpa;
use Google::Ads::GoogleAds::V5::Common::ResponsiveDisplayAdInfo;
use Google::Ads::GoogleAds::V5::Common::AdTextAsset;
use Google::Ads::GoogleAds::V5::Common::AdImageAsset;
use Google::Ads::GoogleAds::V5::Common::ImageAsset;
use Google::Ads::GoogleAds::V5::Enums::BudgetDeliveryMethodEnum qw(STANDARD);
use Google::Ads::GoogleAds::V5::Enums::AdvertisingChannelTypeEnum qw(DISPLAY);
use Google::Ads::GoogleAds::V5::Enums::AdvertisingChannelSubTypeEnum
  qw(DISPLAY_SMART_CAMPAIGN);
use Google::Ads::GoogleAds::V5::Enums::AdGroupStatusEnum;
use Google::Ads::GoogleAds::V5::Enums::AdGroupAdStatusEnum;
use Google::Ads::GoogleAds::V5::Enums::AssetTypeEnum qw(IMAGE);
use
  Google::Ads::GoogleAds::V5::Services::CampaignBudgetService::CampaignBudgetOperation;
use Google::Ads::GoogleAds::V5::Services::CampaignService::CampaignOperation;
use Google::Ads::GoogleAds::V5::Services::AdGroupService::AdGroupOperation;
use Google::Ads::GoogleAds::V5::Services::AdGroupAdService::AdGroupAdOperation;
use Google::Ads::GoogleAds::V5::Services::AssetService::AssetOperation;
use Google::Ads::GoogleAds::V5::Utils::ResourceNames;

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

# They can be used to create an image asset for your customer account only once.
use constant MARKETING_IMAGE_URL        => "https://goo.gl/3b9Wfh";
use constant SQUARE_MARKETING_IMAGE_URL => "https://goo.gl/mtt54n";

# 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";
# Optional: Specify the marketing image asset ID and square marketing image asset
# ID below to be used to create a responsive display ad. If none is specified,
# this example will create a new image assets.
my $marketing_image_asset_id        = undef;
my $square_marketing_image_asset_id = undef;

sub add_smart_display_ad {
  my ($api_client, $customer_id, $marketing_image_asset_id,
    $square_marketing_image_asset_id)
    = @_;

  my $budget_resource_name = create_campaign_budget($api_client, $customer_id);

  my $campaign_resource_name =
    create_smart_display_campaign($api_client, $customer_id,
    $budget_resource_name);

  my $ad_group_resource_name =
    create_ad_group($api_client, $customer_id, $campaign_resource_name);

  create_responsive_display_ad($api_client, $customer_id,
    $ad_group_resource_name, $marketing_image_asset_id,
    $square_marketing_image_asset_id);

  return 1;
}

# Creates a campaign budget.
sub create_campaign_budget {
  my ($api_client, $customer_id) = @_;

  # Create a campaign budget.
  my $campaign_budget =
    Google::Ads::GoogleAds::V5::Resources::CampaignBudget->new({
      name           => "Interplanetary Cruise Budget #" . uniqid(),
      deliveryMethod => STANDARD,
      amountMicros   => 5000000
    });

  # Create a campaign budget operation.
  my $campaign_budget_operation =
    Google::Ads::GoogleAds::V5::Services::CampaignBudgetService::CampaignBudgetOperation
    ->new({
      create => $campaign_budget
    });

  # Issue a mutate request to add the campaign budget.
  my $campaign_budget_response = $api_client->CampaignBudgetService()->mutate({
      customerId => $customer_id,
      operations => [$campaign_budget_operation]});

  # Print out some information about the created campaign budget.
  my $campaign_budget_resource_name =
    $campaign_budget_response->{results}[0]{resourceName};
  printf "Added budget named '%s'.\n", $campaign_budget_resource_name;

  return $campaign_budget_resource_name;
}

# Creates a Smart Display campaign.
sub create_smart_display_campaign {
  my ($api_client, $customer_id, $campaign_budget_resource_name) = @_;

  my $campaign = Google::Ads::GoogleAds::V5::Resources::Campaign->new({
      name => "Smart Display Campaign #" . uniqid(),
      # Smart Display campaign requires the advertising_channel_type as 'DISPLAY'.
      advertisingChannelType => DISPLAY,
      # Smart Display campaign requires the advertising_channel_sub_type as
      # 'DISPLAY_SMART_CAMPAIGN'.
      advertisingChannelSubType => DISPLAY_SMART_CAMPAIGN,
      # Smart Display campaign requires the TargetCpa bidding strategy.
      targetCpa => Google::Ads::GoogleAds::V5::Common::TargetCpa->new({
          targetCpaMicros => 5000000
        }
      ),
      campaignBudget => $campaign_budget_resource_name,
      # Optional: Set the start and end dates for the campaign, beginning one day
      # from now and ending a month from now.
      startDate => strftime("%Y%m%d", localtime(time + 60 * 60 * 24)),
      endDate   => strftime("%Y%m%d", localtime(time + 60 * 60 * 24 * 30)),
    });

  # Create a campaign operation.
  my $campaign_operation =
    Google::Ads::GoogleAds::V5::Services::CampaignService::CampaignOperation->
    new({
      create => $campaign
    });

  # Issue a mutate request to add the campaign.
  my $campaign_response = $api_client->CampaignService()->mutate({
      customerId => $customer_id,
      operations => [$campaign_operation]});

  # Print out some information about the added campaign.
  my $campaign_resource_name =
    $campaign_response->{results}[0]{resourceName};
  printf "Added a Smart Display campaign named '%s'.\n",
    $campaign_resource_name;

  return $campaign_resource_name;
}

# Creates an ad group.
sub create_ad_group {
  my ($api_client, $customer_id, $campaign_resource_name) = @_;

  # Construct an ad group and set its type.
  my $ad_group = Google::Ads::GoogleAds::V5::Resources::AdGroup->new({
    name     => "Earth to Mars Cruises #" . uniqid(),
    campaign => $campaign_resource_name,
    status   => Google::Ads::GoogleAds::V5::Enums::AdGroupStatusEnum::PAUSED
  });

  # Create an ad group operation.
  my $ad_group_operation =
    Google::Ads::GoogleAds::V5::Services::AdGroupService::AdGroupOperation->new(
    {
      create => $ad_group
    });

  # Issue a mutate request to add the ad group.
  my $ad_group_response = $api_client->AdGroupService()->mutate({
      customerId => $customer_id,
      operations => [$ad_group_operation]});

  # Print out some information about the added ad group.
  my $ad_group_resource_name =
    $ad_group_response->{results}[0]{resourceName};
  printf "Added ad group named '%s'.\n", $ad_group_resource_name;

  return $ad_group_resource_name;
}

# Creates a responsive display ad, which is a recommended ad type for Smart
# Display campaigns.
sub create_responsive_display_ad {
  my ($api_client, $customer_id, $ad_group_resource_name,
    $marketing_image_asset_id, $square_marketing_image_asset_id)
    = @_;

  # Create a new image asset for marketing image and square marketing image if
  # there are no assets' IDs specified.
  my $marketing_image_asset_resource_name =
    defined $marketing_image_asset_id
    ? Google::Ads::GoogleAds::V5::Utils::ResourceNames::asset($customer_id,
    $marketing_image_asset_id)
    : create_image_asset($api_client, $customer_id, MARKETING_IMAGE_URL,
    "Marketing Image");

  my $square_marketing_image_asset_resource_name =
    defined $square_marketing_image_asset_id
    ? Google::Ads::GoogleAds::V5::Utils::ResourceNames::asset($customer_id,
    $square_marketing_image_asset_id)
    : create_image_asset($api_client, $customer_id, SQUARE_MARKETING_IMAGE_URL,
    "Square Marketing Image");

  # Create a responsive display ad info.
  my $responsive_display_ad_info =
    Google::Ads::GoogleAds::V5::Common::ResponsiveDisplayAdInfo->new({
      # Set some basic required information for the responsive display ad.
      headlines => [
        Google::Ads::GoogleAds::V5::Common::AdTextAsset->new({
            text => "Travel"
          })
      ],
      longHeadline => Google::Ads::GoogleAds::V5::Common::AdTextAsset->new({
          text => "Travel the World"
        }
      ),
      descriptions => [
        Google::Ads::GoogleAds::V5::Common::AdTextAsset->new({
            text => "Take to the air!"
          })
      ],
      businessName => "Google",
      # Set the marketing image and square marketing image to the previously
      # created image assets.
      marketingImages => [
        Google::Ads::GoogleAds::V5::Common::AdImageAsset->new({
            asset => $marketing_image_asset_resource_name
          })
      ],
      squareMarketingImages => [
        Google::Ads::GoogleAds::V5::Common::AdImageAsset->new({
            asset => $square_marketing_image_asset_resource_name
          })
      ],
      # Optional: Set call to action text, price prefix and promotion text.
      callToActionText => "Shop Now",
      pricePrefix      => "as low as",
      promoText        => "Free shipping!"
    });

  # Create an ad group ad with the created responsive display ad info.
  my $ad_group_ad = Google::Ads::GoogleAds::V5::Resources::AdGroupAd->new({
      adGroup => $ad_group_resource_name,
      status  => Google::Ads::GoogleAds::V5::Enums::AdGroupAdStatusEnum::PAUSED,
      ad      => Google::Ads::GoogleAds::V5::Resources::Ad->new({
          finalUrls           => ["https://www.example.com"],
          responsiveDisplayAd => $responsive_display_ad_info
        })});

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

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

  # Print out some information about the newly created ad.
  my $ad_group_ad_resource_name =
    $ad_group_ad_response->{results}[0]{resourceName};
  printf "Added ad group ad named '%s'.\n", $ad_group_ad_resource_name;
}

# Creates an image asset to be used for creating ads.
sub create_image_asset {
  my ($api_client, $customer_id, $image_url, $image_name) = @_;

  # Create an asset.
  my $asset = Google::Ads::GoogleAds::V5::Resources::Asset->new({
      name       => $image_name,
      type       => IMAGE,
      imageAsset => Google::Ads::GoogleAds::V5::Common::ImageAsset->new({
          data => get_base64_data_from_url($image_url)})});

  # Create an asset operation.
  my $asset_operation =
    Google::Ads::GoogleAds::V5::Services::AssetService::AssetOperation->new({
      create => $asset
    });

  # Issue a mutate request to add the asset.
  my $asset_response = $api_client->AssetService()->mutate({
      customerId => $customer_id,
      operations => [$asset_operation]});

  # Print out information about the newly added asset.
  my $asset_resource_name = $asset_response->{results}[0]{resourceName};
  printf "A new image asset has been added with resource name: '%s'.\n",
    $asset_resource_name;

  return $asset_resource_name;
}

# 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,
  "marketing_image_asset_id=i"     => \$marketing_image_asset_id,
  "square_marketing_image_asset=i" => \$square_marketing_image_asset_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_smart_display_ad($api_client, $customer_id =~ s/-//gr,
  $marketing_image_asset_id, $square_marketing_image_asset_id);

=pod

=head1 NAME

add_smart_display_ad

=head1 DESCRIPTION

This example adds a Smart Display campaign, an ad group and a responsive display
ad. More information about Smart Display campaigns can be found at
https://support.google.com/google-ads/answer/7020281.

IMPORTANT: The AssetService requires you to reuse what you've uploaded previously.
Therefore, you cannot create an image asset with the exactly same bytes. In case
you want to run this example more than once, note down the created assets' IDs
and specify them as command-line arguments for marketing and square marketing
images.

Alternatively, you can modify the image URLs' constants directly to use other images.

=head1 SYNOPSIS

add_smart_display_ad.pl [options]

    -help                                Show the help message.
    -customer_id                         The Google Ads customer ID.
    -marketing_image_asset_id            [optional] The ID of marketing image asset.
    -square_marketing_image_asset_id     [optional] The ID of square marketing image asset.

=cut