Working with Assets

Creating assets

Most asset types must be created using the AssetService before they are used in an ad. TextAssets are the exception and are created inline during ad creation. But all other types must first be uploaded to an advertiser’s account before they can be used.

The following example shows how to create a new image asset from a URL of raw image data.

Java

private void runExample(GoogleAdsClient googleAdsClient, long customerId) throws IOException {
  byte[] imageData = ByteStreams.toByteArray(new URL(IMAGE_URL).openStream());

  // Create the image asset.
  ImageAsset imageAsset = ImageAsset.newBuilder().setData(ByteString.copyFrom(imageData)).build();

  // Creates an asset.
  Asset asset =
      Asset.newBuilder()
          // 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.
          // .setName("Jupiter Trip # " + getPrintableDateTime())
          .setType(AssetType.IMAGE)
          .setImageAsset(imageAsset)
          .build();

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

  // Creates the service client.
  try (AssetServiceClient assetServiceClient =
      googleAdsClient.getLatestVersion().createAssetServiceClient()) {
    // Issues a mutate request to add the asset.
    MutateAssetsResponse response =
        assetServiceClient.mutateAssets(Long.toString(customerId), ImmutableList.of(operation));
    // Prints the result.
    System.out.printf(
        "The image asset with resource name '%s' was created.%n",
        response.getResults(0).getResourceName());
  }
}

C#

public void Run(GoogleAdsClient client, long customerId)
{
    // Get the AssetServiceClient.
    AssetServiceClient assetService =
        client.GetService(Services.V6.AssetService);

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

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

    // 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
    };

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

        // Displays the result.
        Console.WriteLine($"Image asset with resource name: " +
            $"'{response.Results.First().ResourceName}' is created.");
    }
    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)
{
    // Creates an image content.
    $imageContent = file_get_contents(self::IMAGE_URL);

    // Creates an 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 #' . Helper::getPrintableDatetime(),
        'type' => AssetType::IMAGE,
        'image_asset' => new ImageAsset(['data' => $imageContent])
    ]);

    // 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]
    );

    if (!empty($response->getResults())) {
        // Prints the resource name of the added image asset.
        /** @var MutateAssetResult $addedImageAsset */
        $addedImageAsset = $response->getResults()[0];
        printf(
            "The image asset with resource name '%s' was created.%s",
            $addedImageAsset->getResourceName(),
            PHP_EOL
        );
    } else {
        print 'No image asset was created.' . PHP_EOL;
    }
}

Python

def main(client, customer_id):
    """Main method, to run this code example as a standalone application."""

    # Download image from URL
    URL = "https://goo.gl/3b9Wfh"
    image_content = requests.get(URL).content

    asset_operation = client.get_type("AssetOperation", version="v6")
    asset = asset_operation.create
    asset.type = client.get_type("AssetTypeEnum", version="v6").IMAGE
    asset.image_asset.data = image_content
    asset.image_asset.file_size = len(image_content)
    asset.image_asset.mime_type = client.get_type("MimeTypeEnum").IMAGE_JPEG
    # Use your favorite image library to determine dimensions
    asset.image_asset.full_size.height_pixels = 315
    asset.image_asset.full_size.width_pixels = 600
    asset.image_asset.full_size.url = URL
    # 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 = 'Jupiter Trip #' + uuid.uuid4()

    asset_service = client.get_service("AssetService", version="v6")

    try:
        mutate_asset_response = asset_service.mutate_assets(
            customer_id, [asset_operation]
        )
        print("Uploaded file(s):")
        for row in mutate_asset_response.results:
            print(f"\tResource name: {row.resource_name}")

    except GoogleAdsException as ex:
        print(
            f'Request with ID "{ex.request_id}" failed with status '
            f'"{ex.error.code().name}" and includes the following errors:'
        )
        for error in ex.failure.errors:
            print(f'\tError with message "{error.message}".')
            if error.location:
                for field_path_element in error.location.field_path_elements:
                    print(f"\t\tOn field: {field_path_element.field_name}")
        sys.exit(1)

Ruby

def upload_image_asset(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

  url = 'https://goo.gl/3b9Wfh'
  image_data = open(url) { |f| f.read }

  # Create the operation for uploading the image asset.
  asset_operation = client.operation.create_resource.asset do |asset|
    asset.type = :IMAGE
    asset.image_asset = client.resource.image_asset do |image_asset|
      image_asset.data = image_data
      image_asset.file_size = image_data.length()
      image_asset.mime_type = :IMAGE_JPEG
      image_asset.full_size = client.resource.image_dimension do |dimension|
        dimension.height_pixels = 315
        dimension.width_pixels = 600
        dimension.url = url
      end
      # 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.
      # image_asset.name = 'Jupiter Trip #' + SecureRandom.uuid
    end
  end

  # Upload the image asset.
  response = client.service.asset.mutate_assets(
    customer_id: customer_id,
    operations: [asset_operation],
  )

  puts "Uploaded image asset #{response.results.first.resource_name}."
end

Perl

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

  # Create an image content.
  my $image_content = get_base64_data_from_url(IMAGE_URL);

  # Create an asset.
  my $asset = Google::Ads::GoogleAds::V6::Resources::Asset->new({
      # 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 #" . uniqid(),
      type       => IMAGE,
      imageAsset => Google::Ads::GoogleAds::V6::Common::ImageAsset->new({
          data => $image_content
        })});

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

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

  printf "The image asset with resource name '%s' was created.\n",
    $assets_response->{results}[0]{resourceName};

  return 1;
}

After the asset has been created, the API returns a MutateAssetResult object that contains the resource name of the new ImageAsset. This resource name is used to reference the ImageAsset when creating an asset-based ad.

You can retrieve a list existing assets and their resource names by querying the GoogleAdsService. See the Fetching Asset Attribute and Metrics section for more details.

Using assets in ads

Assets are supported by the following ad types, according to the table below.

Ads types and the asset types they support:
AppAd
TextAsset
ImageAsset
VideoAsset
MediaBundleAsset
AppEngagementAd TextAsset
ImageAsset
VideoAsset
DisplayUploadAd MediaBundleAsset
ResponsiveDisplayAd TextAsset
ImageAsset
VideoAsset
ResponsiveSearchAd TextAsset

Each of the above ad types has fields for setting the various asset types that it supports. For TextAsset types, a new string asset is created inline within the Ad. For all other types, existing asset are added to the Ad by referencing their resource names.

The example below demonstrates adding TextAssets and ImageAssets to create a ResponsiveDisplayAd. The TextAssets are created inline as the ad’s headlines and description. The ImageAsset are specified by resource name as the ad’s logo images.

Java

private void createAd(
    GoogleAdsClient googleAdsClient, long customerId, String adGroupResourceName)
    throws IOException {
  String marketingImageUrl = "https://goo.gl/3b9Wfh";
  String marketingImageName = "Marketing Image";
  String marketingImageResourceName =
      uploadAsset(googleAdsClient, customerId, marketingImageUrl, marketingImageName);
  String squareMarketingImageName = "Square Marketing Image";
  String squareMarketingImageUrl = "https://goo.gl/mtt54n";
  String squareMarketingImageResourceName =
      uploadAsset(googleAdsClient, customerId, squareMarketingImageUrl, squareMarketingImageName);

  // Creates the responsive display ad info object.
  ResponsiveDisplayAdInfo responsiveDisplayAdInfo =
      ResponsiveDisplayAdInfo.newBuilder()
          .addMarketingImages(
              AdImageAsset.newBuilder().setAsset(marketingImageResourceName).build())
          .addSquareMarketingImages(
              AdImageAsset.newBuilder().setAsset(squareMarketingImageResourceName).build())
          .addHeadlines(AdTextAsset.newBuilder().setText("Travel").build())
          .setLongHeadline(AdTextAsset.newBuilder().setText("Travel the World").build())
          .addDescriptions(AdTextAsset.newBuilder().setText("Take to the air!").build())
          .setBusinessName("Interplanetary Cruises")
          // Optional: Call to action text.
          // Valid texts: https://support.google.com/adwords/answer/7005917
          .setCallToActionText("Apply Now")
          // Optional: Sets the ad colors.
          .setMainColor("#0000ff")
          .setAccentColor("#ffff00")
          // Optional: Sets to false to strictly render the ad using the colors.
          .setAllowFlexibleColor(false)
          // Optional: Sets the format setting that the ad will be served in.
          .setFormatSetting(DisplayAdFormatSetting.NON_NATIVE)
          // Optional: Creates a logo image and sets it to the ad.
          /*
          .addLogoImages(
              AdImageAsset.newBuilder()
                  .setAsset(StringValue.of("INSERT_LOGO_IMAGE_RESOURCE_NAME_HERE"))
                  .build())
          */
          // Optional: Creates a square logo image and sets it to the ad.
          /*
          .addSquareLogoImages(
              AdImageAsset.newBuilder()
                  .setAsset(StringValue.of("INSERT_SQUARE_LOGO_IMAGE_RESOURCE_NAME_HERE"))
                  .build())
          */
          .build();

  // Creates the ad.
  Ad ad =
      Ad.newBuilder()
          .setResponsiveDisplayAd(responsiveDisplayAdInfo)
          .addFinalUrls("http://www.example.com/")
          .build();

  // Creates the ad group ad.
  AdGroupAd adGroupAd = AdGroupAd.newBuilder().setAdGroup(adGroupResourceName).setAd(ad).build();

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

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

C#

public void Run(GoogleAdsClient client, long customerId, long merchantCenterAccountId,
    long campaignBudgetId, long userListId)
{
    try
    {
        // Creates a shopping campaign associated with a given Merchant Center account.
        string campaignResourceName = CreateCampaign(client, customerId,
            merchantCenterAccountId, campaignBudgetId);

        // Creates an ad group for the campaign.
        string adGroupResourceName = CreateAdGroup(client, customerId,
            campaignResourceName);

        // Creates a responsive display ad in the ad group.
        CreateAd(client, customerId, adGroupResourceName);

        // Targets a specific user list for remarketing.
        AttachUserList(client, customerId, adGroupResourceName, userListId);
    }
    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 $merchantCenterAccountId,
    int $campaignBudgetId,
    int $userListId
) {
    // Creates a shopping campaign associated with a given merchant center account.
    $campaignResourceName = self::createCampaign(
        $googleAdsClient,
        $customerId,
        $merchantCenterAccountId,
        $campaignBudgetId
    );

    // Creates an ad group for the campaign.
    $adGroupResourceName =
        self::createAdGroup($googleAdsClient, $customerId, $campaignResourceName);

    // Creates a dynamic display ad in the ad group.
    self::createAd($googleAdsClient, $customerId, $adGroupResourceName);

    // Targets a specific user list for remarketing.
    self::attachUserList($googleAdsClient, $customerId, $adGroupResourceName, $userListId);
}

Python

def main(
    client,
    customer_id,
    merchant_center_account_id,
    campaign_budget_id,
    user_list_id,
):
    """Creates a campaign associated with an existing Merchant Center account.

    Args:
        client: An initialized GoogleAds client.
        customer_id: The Google Ads customer ID.
        merchant_center_account_id: The target Merchant Center account ID.
        campaign_budget_id: The ID of the campaign budget to utilize.
        user_list_id: The ID of the user list to target for remarketing.
    """
    try:
        # Create a shopping campaign associated with a given Merchant Center
        # account.
        campaign_resource_name = _create_campaign(
            client, customer_id, merchant_center_account_id, campaign_budget_id
        )

        # Create an ad group for the campaign.
        ad_group_resource_name = _create_ad_group(
            client, customer_id, campaign_resource_name
        )

        # Create a dynamic display ad in the ad group.
        _create_ad(client, customer_id, ad_group_resource_name)

        # Target a specific user list for remarketing.
        _attach_user_list(
            client, customer_id, ad_group_resource_name, user_list_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)


def _create_campaign(
    client, customer_id, merchant_center_account_id, campaign_budget_id
):
    """Creates a campaign linked to a Merchant Center product feed.

    Args:
        client: An initialized GoogleAds client.
        customer_id: The Google Ads customer ID.
        merchant_center_account_id: The target Merchant Center account ID.
        campaign_budget_id: The ID of the campaign budget to utilize.
    Returns:
        The string resource name of the newly created campaign.
    """
    # Gets the CampaignService client.
    campaign_service = client.get_service("CampaignService", version="v6")

    # Creates a campaign operation and configures the new campaign.
    campaign_operation = client.get_type("CampaignOperation", version="v6")
    campaign = campaign_operation.create
    campaign.name = f"Shopping campaign #{uuid4()}"
    # Configures the settings for the shopping campaign.
    campaign.shopping_setting.campaign_priority = 0
    # This connects the campaign to the Merchant Center account.
    campaign.shopping_setting.merchant_id = merchant_center_account_id
    # Display Network campaigns do not support partition by country. The only
    # supported value is "ZZ". This signals that products from all countries are
    # available in the campaign. The actual products which serve are based on
    # the products tagged in the user list entry.
    campaign.shopping_setting.sales_country = "ZZ"
    campaign.shopping_setting.enable_local = True
    # Dynamic remarketing campaigns are only available on the Google Display
    # Network.
    campaign.advertising_channel_type = client.get_type(
        "AdvertisingChannelTypeEnum", version="v6"
    ).DISPLAY
    campaign.status = client.get_type("CampaignStatusEnum", version="v6").PAUSED
    campaign.campaign_budget = client.get_service(
        "CampaignBudgetService", version="v6"
    ).campaign_budget_path(customer_id, campaign_budget_id)
    campaign.manual_cpc.CopyFrom(client.get_type("ManualCpc", version="v6"))

    # Issues a mutate request to add the campaign.
    campaign_response = campaign_service.mutate_campaigns(
        customer_id, [campaign_operation]
    )
    campaign_resource_name = campaign_response.results[0].resource_name
    print(f"Created campaign with resource name '{campaign_resource_name}'.")

    return campaign_resource_name


def _create_ad_group(client, customer_id, campaign_resource_name):
    """Creates an ad group for the remarketing campaign.

    Args:
        client: An initialized GoogleAds client.
        customer_id: The Google Ads customer ID.
        campaign_resource_name: The resource name of the target campaign.
    Returns:
        The string resource name of the newly created ad group.
    """
    # Gets the AdGroupService.
    ad_group_service = client.get_service("AdGroupService", version="v6")

    # Creates an ad group operation and configures the new ad group.
    ad_group_operation = client.get_type("AdGroupOperation", version="v6")
    ad_group = ad_group_operation.create
    ad_group.name = "Dynamic remarketing ad group"
    ad_group.campaign = campaign_resource_name
    ad_group.status = client.get_type("AdGroupStatusEnum", version="v6").ENABLED

    # Issues a mutate request to add the ad group.
    ad_group_response = ad_group_service.mutate_ad_groups(
        customer_id, [ad_group_operation]
    )
    ad_group_resource_name = ad_group_response.results[0].resource_name

    return ad_group_resource_name


def _create_ad(client, customer_id, ad_group_resource_name):
    """Creates the responsive display ad.

    Args:
        client: An initialized GoogleAds client.
        customer_id: The Google Ads customer ID.
        ad_group_resource_name: The resource name of the target ad group.
    """
    # Get the AdGroupAdService client.
    ad_group_ad_service = client.get_service("AdGroupAdService", version="v6")

    # Upload image assets for the ad.
    marketing_image_resource_name = _upload_image_asset(
        client, customer_id, "https://goo.gl/3b9Wfh", "Marketing Image"
    )
    square_marketing_image_resource_name = _upload_image_asset(
        client, customer_id, "https://goo.gl/mtt54n", "Square Marketing Image"
    )

    # Create the relevant asset objects for the ad.
    marketing_image = client.get_type("AdImageAsset", version="v6")
    marketing_image.asset = marketing_image_resource_name
    square_marketing_image = client.get_type("AdImageAsset", version="v6")
    square_marketing_image.asset = square_marketing_image_resource_name
    headline = client.get_type("AdTextAsset", version="v6")
    headline.text = "Travel"
    description = client.get_type("AdTextAsset", version="v6")
    description.text = "Take to the air!"

    # Create an ad group ad operation and set the ad group ad values.
    ad_group_ad_operation = client.get_type("AdGroupAdOperation", version="v6")
    ad_group_ad = ad_group_ad_operation.create
    ad_group_ad.ad_group = ad_group_resource_name
    ad_group_ad.ad.final_urls.append("http://www.example.com/")

    # Configure the responsive display ad info object.
    responsive_display_ad_info = ad_group_ad.ad.responsive_display_ad
    responsive_display_ad_info.marketing_images.append(marketing_image)
    responsive_display_ad_info.square_marketing_images.append(
        square_marketing_image
    )
    responsive_display_ad_info.headlines.append(headline)
    responsive_display_ad_info.long_headline.text = "Travel the World"
    responsive_display_ad_info.descriptions.append(description)
    responsive_display_ad_info.business_name = "Interplanetary Cruises"
    # Optional: Call to action text.
    # Valid texts: https://support.google.com/google-ads/answer/7005917
    responsive_display_ad_info.call_to_action_text = "Apply Now"
    # Optional: Set the ad colors.
    responsive_display_ad_info.main_color = "#0000ff"
    responsive_display_ad_info.accent_color = "#ffff00"
    # Optional: Set to false to strictly render the ad using the colors.
    responsive_display_ad_info.allow_flexible_color = False
    # Optional: Set the format setting that the ad will be served in.
    responsive_display_ad_info.format_setting = client.get_type(
        "DisplayAdFormatSettingEnum", version="v6"
    ).NON_NATIVE
    # Optional: Create a logo image and set it to the ad.
    # logo_image = client.get_type("AdImageAsset", version="v6")
    # logo_image.asset = "INSERT_LOGO_IMAGE_RESOURCE_NAME_HERE"
    # responsive_display_ad_info.logo_images.append(logo_image)
    # Optional: Create a square logo image and set it to the ad.
    # square_logo_image = client.get_type("AdImageAsset", version="v6")
    # square_logo_image.asset = "INSERT_SQUARE_LOGO_IMAGE_RESOURCE_NAME_HERE"
    # responsive_display_ad_info.square_logo_images.append(square_logo_image)

    # Issue a mutate request to add the ad group ad.
    ad_group_ad_response = ad_group_ad_service.mutate_ad_group_ads(
        customer_id, [ad_group_ad_operation]
    )
    print(
        "Created ad group ad with resource name "
        f"'{ad_group_ad_response.results[0].resource_name}'."
    )


def _upload_image_asset(client, customer_id, image_url, asset_name):
    """Adds an image asset to the Google Ads account.

    Args:
        client: An initialized GoogleAds client.
        customer_id: The Google Ads customer ID.
        image_url: The URL of the image source.
        asset_name: The string label for this image asset.
    Returns:
        The string resource name of the newly uploaded image asset.
    """
    # Get the AssetService client.
    asset_service = client.get_service("AssetService", version="v6")

    # Fetch the image data.
    image_data = requests.get(image_url).content

    # Create an asset operation and set the image asset values.
    asset_operation = client.get_type("AssetOperation", version="v6")
    asset = asset_operation.create
    asset.type = client.get_type("AssetTypeEnum", version="v6").IMAGE
    asset.image_asset.data = image_data
    asset.name = asset_name

    mutate_asset_response = asset_service.mutate_assets(
        customer_id, [asset_operation]
    )
    image_asset_resource_name = mutate_asset_response.results[0].resource_name
    print(
        "Created image asset with resource name "
        f"'{image_asset_resource_name}'."
    )

    return image_asset_resource_name


def _attach_user_list(
    client, customer_id, ad_group_resource_name, user_list_id
):
    """Targets a user list with an ad group.

    Args:
        client: An initialized GoogleAds client.
        customer_id: The Google Ads customer ID.
        ad_group_resource_name: The resource name of the target ad group.
        user_list_id: The ID of the user list to target for remarketing.
    """
    # Get the AdGroupCriterionService client.
    ad_group_criterion_service = client.get_service(
        "AdGroupCriterionService", version="v6"
    )

    # Create an ad group criterion operation and set the ad group criterion
    # values.
    ad_group_criterion_operation = client.get_type(
        "AdGroupCriterionOperation", version="v6"
    )
    ad_group_criterion = ad_group_criterion_operation.create
    ad_group_criterion.ad_group = ad_group_resource_name
    ad_group_criterion.user_list.user_list = client.get_service(
        "UserListService", version="v6"
    ).user_list_path(customer_id, user_list_id)

    # Issue a mutate request to add the ad group criterion.
    ad_group_criterion_response = ad_group_criterion_service.mutate_ad_group_criteria(
        customer_id, [ad_group_criterion_operation]
    )
    print(
        "Created ad group criterion with resource name "
        f"'{ad_group_criterion_response.results[0].resource_name}'."
    )

Ruby

def add_merchant_center_dynamic_remarketing_campaign(
  customer_id,
  merchant_center_id,
  campaign_budget_id,
  user_list_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 shopping campaign associated with a given merchant center account.
  campaign_resource_name = create_campaign(
    client,
    customer_id,
    merchant_center_id,
    campaign_budget_id
  )

  # Creates an ad group for the campaign.
  ad_group_resource_name = create_ad_group(client, customer_id,
                                           campaign_resource_name)

  # Creates a dynamic display ad in the ad group.
  create_ad(client, customer_id, ad_group_resource_name)

  # Targets a specific user list for remarketing.
  attach_user_list(client, customer_id, ad_group_resource_name, user_list_id)
end

Perl

sub add_merchant_center_dynamic_remarketing_campaign {
  my ($api_client, $customer_id, $merchant_center_account_id,
    $campaign_budget_id, $user_list_id)
    = @_;

  # Create a shopping campaign associated with a given Merchant Center account.
  my $campaign_resource_name =
    create_campaign($api_client, $customer_id, $merchant_center_account_id,
    $campaign_budget_id);

  # Create an ad group for the campaign.
  my $ad_group_resource_name =
    create_ad_group($api_client, $customer_id, $campaign_resource_name);

  # Create a dynamic display ad in the ad group.
  create_ad($api_client, $customer_id, $ad_group_resource_name);

  # Target a specific user list for remarketing.
  attach_user_list($api_client, $customer_id, $ad_group_resource_name,
    $user_list_id);

  return 1;
}