Creatives

Overview

In Real-time Bidding, bidders compete in an auction to place creatives for a given impression. However, in order to ensure that creatives meet quality standards, adhere to Google's policies, and fulfill other criteria, they must be reviewed and approved before being placed in a bid.

The Creatives resource allows buyers to submit creatives for review, view the policy compliance of submitted creatives, and patch existing creatives. It enables bidders to review the policy compliance of submitted creatives for all associated buyer accounts either directly or through a Google Cloud Pub/Sub subscription.

Life cycle of a creative

The following describes actions that can be taken on a creative over time:

  • Creation: A creative can be submitted for review with buyers.creatives.create.
  • Review: A creative undergoes review to determine which contexts (if any) it will be permitted to be placed in bids. The creative review process is typically completed 30 minutes following its submission.

  • Activation: Immediately following review, a creative becomes active. If it has been approved for use in one or more context, it can be placed in bids for applicable inventory received from the Real-time Bidding service. Otherwise, bids placed with the creative will be filtered from the auction.

  • Modification: After a creative's review has been completed, it can be modified with buyers.creatives.patch, which will cause it to be resubmitted for review.

  • Deactivation: A creative will become inactive after 30 days pass where it is not used in Real-time bidding. An inactive creative will not be returned in API responses, but will become active again—and resume appearing in API responses—if a bid is placed with it.

Understanding the CreativeServingDecision

When a creative is reviewed, its creativeServingDecision is populated with detected attributes and policy compliance fields that determine the kind of inventory that it is eligible for.

Detected attributes

Detected attributes are used to correct declared attributes, as well as describe other attributes of the creative that are found during review. These can impact the creative's policy compliance, but can also determine whether the creative is eligible for inventory at a more granular level; for example, if the creative has any detectedAttributes that are found in a bid request's excluded_attribute, a bid placed for that inventory including that creative will be filtered from the auction.

Policy compliance

Every creative is reviewed and has its creativeServingDecision populated with dealsPolicyCompliance, networkPolicyCompliance, platformPolicyCompliance, chinaPolicyCompliance, and russiaPolicyCompliance. When a bid is placed in Real-time Bidding, the bidder must specify a creative that is compliant with all applicable policies for the inventory, or otherwise have their bid filtered from the auction.

For a given use-case's policy compliance, its status suggests whether the creative was approved for that use-case, and topics is populated for disapproved creatives to provide additional context about the disapproval. Each PolicyTopicEntry includes a policyTopic describing a factor that caused the creative's disapproval, a helpCenterUrl linking to an article that provides additional details about the policy topic, and evidences that clarify how the creative violated the policy.

Examples

Creative approved for all use-cases

A creative with a creativeServingDecision such as the one below would not be restricted from serving in the open auction, deals, open bidding, or from being placed in China or Russia. However, detected attributes like detectedAttributes, detectedLanguages, and detectedProductCategories can still impact which bid requests a bidder can respond to with the creative.

{
  "chinaPolicyCompliance": {
    "status": "APPROVED"
  },
  "dealsPolicyCompliance": {
    "status": "APPROVED"
  },
  "detectedAttributes": [
    "CREATIVE_TYPE_HTML"
  ],
  "detectedLanguages": [
    "en"
  ],
  "detectedProductCategories": [
    10016,
    10019,
    10141,
    10168,
    10754,
    10885,
    12206
  ],
  "lastStatusUpdate": "2020-07-30T04:47:31.616018Z",
  "networkPolicyCompliance": {
    "status": "APPROVED"
  },
  "platformPolicyCompliance": {
    "status": "APPROVED"
  },
  "russiaPolicyCompliance": {
    "status": "APPROVED"
  }
}

Creative with disapproved policy compliance

In addition to detected attributes, the following creativeServingDecision indicates that the creative is not permitted to serve in deals or the open auction via dealsPolicyCompliance and networkPolicyCompliance having their status set to DISAPPROVED. If applicable, additional context for the disapproval will be provided under topics. In this case, the policyTopic suggests that the creative was disapproved for the open auction because the creative's destination URL was not crawlable during its review, and it was detected to promote online pharmaceutical products. The provided Help Center URLs link to relevant articles describing the policies that were violated and resulted in the creative being disapproved. Finally, the evidence includes the creative's destination URL that could not be crawled during the review.

The creative is also disapproved for use in China and Russia. Note that at this time, policy topics and evidence will not typically be populated for either of these.

{
  "detectedAdvertisers": [
    {
      "advertiserId": "22114433",
      "advertiserName": "Test Advertiser"
    }
  ],
  "detectedAttributes": [
    "RICH_MEDIA_CAPABILITY_TYPE_SSL"
  ],
  "lastStatusUpdate": "2020-10-16T23:20:26.140810Z",
  "dealsPolicyCompliance": {
    "status": "APPROVED"
  },
  "networkPolicyCompliance": {
    "status": "DISAPPROVED",
    "topics": [
      {
        "policyTopic": "ONLINE_PHARMACY_CERTIFICATION_REQUIRED",
        "helpCenterUrl": "https://support.google.com/authorizedbuyers/answer/6100448"
      },
      {
        "policyTopic": "DESTINATION_NOT_CRAWLABLE",
        "helpCenterUrl": "https://support.google.com/authorizedbuyers/answer/6272857",
        "evidences": [
          {
            "destinationNotWorking": {
              "httpError": 403,
              "expandedUrl": "https://www.milkywaypharma.com/content/en_earth_us/find-plan?query=QUxJRU5fRVhQT1NVUkVfUVVBUkFOVElORQ",
              "lastCheckTime": "2020-10-17T22:32:05Z"
            }
          }
        ]
      }
    ]
  },
  "platformPolicyCompliance": {
    "status": "APPROVED"
  },
  "chinaPolicyCompliance": {
    "status": "DISAPPROVED"
  },
  "russiaPolicyCompliance": {
    "status": "DISAPPROVED"
  }
}

Using the Creatives resource as a buyer

Submit a creative with HTML content for review

The following demonstrates how a simple creative with HTML content can be created and submitted for review with buyers.creatives.create.

REST

Request

POST https://realtimebidding.googleapis.com/v1/buyers/<INSERT_ACCOUNT_ID_HERE>/creatives?alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json
 
{
  "advertiserName": "Test",
  "creativeId": "HTML_Creative_d71e7cd9-8179-4683-ac5c-a203a9c660f2",
  "declaredAttributes": [
    "CREATIVE_TYPE_HTML"
  ],
  "declaredClickThroughUrls": [
    "http://test.com"
  ],
  "declaredRestrictedCategories": [],
  "declaredVendorIds": [],
  "html": {
    "snippet": "<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 scrolling=no src=\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%\"></iframe>",
    "height": 250,
    "width": 300
  }
}

Response

{
  "name": "buyers/<ACCOUNT_ID>/creatives/HTML_Creative_d71e7cd9-8179-4683-ac5c-a203a9c660f2",
  "accountId": "<ACCOUNT_ID>",
  "creativeId": "HTML_Creative_d71e7cd9-8179-4683-ac5c-a203a9c660f2",
  "html": {
    "snippet": "<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 scrolling=no src=\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%\"></iframe>",
    "width": 300,
    "height": 250
  },
  "creativeFormat": "HTML",
  "declaredClickThroughUrls": [
    "http://test.com"
  ],
  "declaredAttributes": [
    "CREATIVE_TYPE_HTML"
  ],
  "advertiserName": "Test",
  "version": 1,
  "apiUpdateTime": "2020-08-06T23:49:52.630384Z",
  "creativeServingDecision": {
    "lastStatusUpdate": "2020-08-06T23:49:52.710Z",
    "dealsPolicyCompliance": {
      "status": "PENDING_REVIEW"
    },
    "networkPolicyCompliance": {
      "status": "PENDING_REVIEW"
    },
    "platformPolicyCompliance": {
      "status": "PENDING_REVIEW"
    },
    "chinaPolicyCompliance": {
      "status": "PENDING_REVIEW"
    },
    "russiaPolicyCompliance": {
      "status": "PENDING_REVIEW"
    }
  }
}

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.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Buyers.Creatives
{
    /// <summary>
    /// Creates a creative with HTML content for the given buyer account ID.
    /// </summary>
    public class CreateHtmlCreatives : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public CreateHtmlCreatives()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get { return "This code example creates a creative with HTML content for the given " +
                         "buyer account ID."; }
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            bool showHelp = false;

            string accountId = null;
            string advertiserName = null;
            string creativeId = null;
            IList<string> declaredAttributes = new List<string>();
            IList<string> declaredClickUrls = new List<string>();
            IList<string> declaredRestrictedCategories = new List<string>();
            IList<int?> declaredVendorIds = new List<int?>();
            string htmlSnippet = null;
            int? htmlHeight = null;
            int? htmlWidth = null;

            var defaultHtmlSnippet = "<iframe marginwidth=0 marginheight=0 height=600 " +
                "frameborder=0 width=160 scrolling=no " +
                "src=\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%" +
                "&wprice=%%WINNING_PRICE_ESC%%\"></iframe>";

            OptionSet options = new OptionSet {
                "Creates a creative with HTML content for the given buyer account ID.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the buyers resource under which the " +
                     "creatives were created. This will be used to construct the name used as " +
                     "a path parameter for the creatives.get request."),
                    a => accountId = a
                },
                {
                    "advertiser_name=",
                    "The name of the company being advertised in the creative.",
                    advertiser_name => advertiserName = advertiser_name
                },
                {
                    "c|creative_id=",
                    ("The user-specified creative ID. The maximum length of the creative ID is " +
                     "128 bytes."),
                    c => creativeId = c
                },
                {
                    "declared_attributes=",
                    ("The creative attributes being declared. Specify this argument for each " +
                     "value you intend to include."),
                    declared_attributes => declaredAttributes.Add(declared_attributes)
                },
                {
                    "declared_click_urls=",
                    ("The click-through URLs being declared. Specify this argument for each " +
                     "value you intend to include."),
                    declared_click_through_urls => declaredClickUrls.Add(
                        declared_click_through_urls)
                },
                {
                    "declared_restricted_categories=",
                    ("The restricted categories being declared. Specify this argument for each " +
                    "value you intend to include."),
                    declared_restricted_categories => declaredRestrictedCategories.Add(
                        declared_restricted_categories)
                },
                {
                    "declared_vendor_ids=",
                    ("The vendor IDs being declared. Specify this argument for each value you " +
                     "intend to include."),
                    (int declared_vendor_ids) => declaredVendorIds.Add(declared_vendor_ids)
                },
                {
                    "html_snippet=",
                    "The HTML snippet that displays the ad when inserted in the web page.",
                    html_snippet => htmlSnippet = html_snippet
                },
                {
                    "html_height=",
                    "The height of the HTML snippet in pixels.",
                    (int html_height) => htmlHeight = html_height
                },
                {
                    "html_width=",
                    "The width of the HTML snippet in pixels.",
                    (int html_width) => htmlWidth = html_width
                },
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Handle error conditions.
            if(extras.Count > 0)
            {
                Console.Error.WriteLine("Unknown arguments specified:");
                foreach(string arg in extras)
                {
                    Console.Error.WriteLine(arg);
                }
                Environment.Exit(1);
            }
            // Verify required arguments were set.
            if(accountId == null)
            {
                Console.Error.WriteLine("Required argument \"account_id\" not specified.");
                options.WriteOptionDescriptions(Console.Error);
                Environment.Exit(1);
            }
            else
            {
                parsedArgs["accountId"] = accountId;
            }

            // Set optional arguments.
            parsedArgs["advertiser_name"] = advertiserName ?? "Test";
            parsedArgs["creative_id"] = creativeId ?? String.Format(
                "HTML_Creative_{0}",
                System.Guid.NewGuid());

            if (declaredAttributes.Count == 0)
            {
                declaredAttributes.Add("CREATIVE_TYPE_HTML");
            }
            parsedArgs["declared_attributes"] = declaredAttributes;

            if (declaredClickUrls.Count == 0)
            {
                declaredClickUrls.Add("http://test.com");
            }

            parsedArgs["declared_click_urls"] = declaredClickUrls;
            parsedArgs["declared_restricted_categories"] = declaredRestrictedCategories;
            parsedArgs["declared_vendor_ids"] = declaredVendorIds;
            parsedArgs["html_snippet"] = htmlSnippet ?? defaultHtmlSnippet;
            parsedArgs["html_height"] = htmlHeight ?? 250;
            parsedArgs["html_width"] = htmlWidth ?? 300;

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            string accountId = (string) parsedArgs["accountId"];
            string parent = $"buyers/{accountId}";

            HtmlContent htmlContent = new HtmlContent();
            htmlContent.Snippet = (string) parsedArgs["html_snippet"];
            htmlContent.Height = (int) parsedArgs["html_height"];
            htmlContent.Width = (int) parsedArgs["html_width"];

            Creative newCreative = new Creative();
            newCreative.AdvertiserName = (string) parsedArgs["advertiser_name"];
            newCreative.CreativeId = (string) parsedArgs["creative_id"];
            newCreative.DeclaredAttributes = (IList<string>) parsedArgs["declared_attributes"];
            newCreative.DeclaredClickThroughUrls = (IList<string>) parsedArgs[
                "declared_click_urls"];
            newCreative.DeclaredRestrictedCategories = (IList<string>) parsedArgs[
                "declared_restricted_categories"];
            newCreative.DeclaredVendorIds = (IList<int?>) parsedArgs["declared_vendor_ids"];
            newCreative.Html = htmlContent;

            BuyersResource.CreativesResource.CreateRequest request =
                rtbService.Buyers.Creatives.Create(newCreative, parent);
            Creative response = null;

            Console.WriteLine("Creating HTML creative for buyer: {0}", parent);

            try
            {
                response = request.Execute();
            }
            catch (System.Exception exception)
            {
                Console.Error.WriteLine("Real-time Bidding API returned error response:\n{0}",
                                        exception.Message);
                Environment.Exit(1);
            }

            Utilities.PrintCreative(response);
        }
    }
}

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.api.services.samples.authorizedbuyers.realtimebidding.v1.buyers.creatives;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.Creative;
import com.google.api.services.realtimebidding.v1.model.HtmlContent;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.UUID;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/**
 * Creates a creative with HTML content for the given buyer account ID.
 */
public class CreateHtmlCreatives {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) {
    Integer accountId = parsedArgs.getInt("account_id");

    String parentBuyerName = String.format("buyers/%s", accountId);

    HtmlContent htmlContent = new HtmlContent();
    htmlContent.setSnippet(parsedArgs.getString("html_snippet"));
    htmlContent.setHeight(parsedArgs.getInt("html_height"));
    htmlContent.setWidth(parsedArgs.getInt("html_width"));

    Creative newCreative = new Creative();
    newCreative.setAdvertiserName(parsedArgs.getString("advertiser_name"));
    newCreative.setCreativeId(parsedArgs.getString("creative_id"));
    newCreative.setDeclaredAttributes(parsedArgs.<String>getList("declared_attributes"));
    newCreative.setDeclaredClickThroughUrls(parsedArgs.<String>getList("declared_click_urls"));
    newCreative.setDeclaredRestrictedCategories(parsedArgs.<String>getList("declared_restricted_categories"));
    newCreative.setDeclaredVendorIds(parsedArgs.<Integer>getList("declared_vendor_ids"));
    newCreative.setHtml(htmlContent);

    Creative creative = null;
    try {
      creative = client.buyers().creatives().create(parentBuyerName, newCreative).execute();
    } catch(IOException ex) {
    System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
    System.exit(1);
  }

    System.out.printf("Created creative for buyer Account ID '%s':\n", accountId);
    Utils.printCreative(creative);
  }

  public static void main(String[] args) {
    ArgumentParser parser = ArgumentParsers.newFor("CreateHtmlCreatives").build()
        .defaultHelp(true)
        .description(("Creates an HTML creative for the given buyer account ID."));
    parser.addArgument("-a", "--account_id")
        .help("The resource ID of the buyers resource under which the creative is to be created. ")
        .required(true)
        .type(Integer.class);
    parser.addArgument("--advertiser_name")
        .help("The name of the company being advertised in the creative.")
        .setDefault("Test");
    parser.addArgument("-c", "--creative_id")
        .help("The user-specified creative ID. The maximum length of the creative ID is 128 bytes.")
        .setDefault(String.format("HTML_Creative_%s", UUID.randomUUID()));
    parser.addArgument("--declared_attributes")
        .help("The creative attributes being declared. Specify each attribute separated by a " +
            "space.")
        .nargs("*")
        .setDefault(Collections.singletonList("CREATIVE_TYPE_HTML"));
    parser.addArgument("--declared_click_urls")
        .help("The click-through URLs being declared. Specify each URL separated by a space.")
        .nargs("*")
        .setDefault(Collections.singletonList("http://test.com"));
    parser.addArgument("--declared_restricted_categories")
        .help("The restricted categories being declared. Specify each category separated by a " +
            "space.")
        .nargs("*");
    parser.addArgument("--declared_vendor_ids")
        .help("The vendor IDs being declared. Specify each ID separated by a space.")
        .type(Integer.class)
        .nargs("*");
    parser.addArgument("--html_snippet")
        .help("The HTML snippet that displays the ad when inserted in the web page.")
        .setDefault("<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 " +
            "scrolling=no src=\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%" +
            "&wprice=%%WINNING_PRICE_ESC%%\"></iframe>");
    parser.addArgument("--html_height")
        .help("The height of the HTML snippet in pixels.")
        .type(Integer.class)
        .setDefault(250);
    parser.addArgument("--html_width")
        .help("The width of the HTML snippet in pixels.")
        .type(Integer.class)
        .setDefault(300);


    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:\n%s", ex);
      System.exit(1);
    }

    execute(client, parsedArgs);
  }
}

PHP

<?php

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

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Buyers_Creatives;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;
use Google_Service_RealTimeBidding_Creative;
use Google_Service_RealTimeBidding_HtmlContent;

/**
 * This example illustrates how to create HTML creatives for a given buyer account.
 */
class CreateHtmlCreatives extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Account ID',
                'description' =>
                    'The resource ID of the buyers resource under which the creative is to be ' .
                    'created.',
                'required' => true
            ],
            [
                'name' => 'advertiser_name',
                'display' => 'Advertiser name',
                'description' => 'The name of the company being advertised in the creative.',
                'required' => false,
                'default' => 'Test'
            ],
            [
                'name' => 'creative_id',
                'display' => 'Creative ID',
                'description' =>
                    'The user-specified creative ID. The maximum length of the creative ID is ' .
                    '128 bytes',
                'required' => false,
                'default' => 'HTML_Creative_' . uniqid()
            ],
            [
                'name' => 'declared_attributes',
                'display' => 'Declared attributes',
                'description' =>
                    'The creative attributes being declared. Specify each attribute separated ' .
                    'by a comma.',
                'required' => false,
                'is_array' => true,
                'default' => ['CREATIVE_TYPE_HTML']
            ],
            [
                'name' => 'declared_click_urls',
                'display' => 'Declared click URLs',
                'description' =>
                    'The click-through URLs being declared. Specify each URL separated by a ' .
                    'comma.',
                'required' => false,
                'is_array' => true,
                'default' => ['http://test.com']
            ],
            [
                'name' => 'declared_restricted_categories',
                'display' => 'Declared restricted categories',
                'description' =>
                    'The restricted categories being declared. Specify each category separated ' .
                    'by a comma.',
                'required' => false,
                'is_array' => true
            ],
            [
                'name' => 'declared_vendor_ids',
                'display' => 'Declared vendor IDs',
                'description' =>
                    'The vendor IDs being declared. Specify each ID separated by a comma.',
                'required' => false,
                'is_array' => true
            ],
            [
                'name' => 'html_snippet',
                'display' => 'HTML snippet',
                'description' =>
                    'The HTML snippet that displays the ad when inserted in the web page.',
                'required' => false,
                'default' =>
                    '<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 ' .
                    'scrolling=no src=\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%' .
                    '&wprice=%%WINNING_PRICE_ESC%%\"></iframe>'
            ],
            [
                'name' => 'html_height',
                'display' => 'Height',
                'description' => 'The height of the HTML snippet in pixels.',
                'required' => false,
                'default' => 250
            ],
            [
                'name' => 'html_width',
                'display' => 'Width',
                'description' => 'The width of the HTML snippet in pixels.',
                'required' => false,
                'default' => 300
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;
        $parentName = "buyers/$values[account_id]";

        $html = new Google_Service_RealTimeBidding_HtmlContent();
        $html->snippet = $values['html_snippet'];
        $html->height = $values['html_height'];
        $html->width = $values['html_width'];

        $newCreative = new Google_Service_RealTimeBidding_Creative();
        $newCreative->advertiserName = $values['advertiser_name'];
        $newCreative->creativeId = $values['creative_id'];
        $newCreative->declaredAttributes = $values['declared_attributes'];
        $newCreative->declaredClickThroughUrls = $values['declared_click_urls'];
        $newCreative->declaredRestrictedCategories = $values['declared_restricted_categories'];
        $newCreative->declaredVendorIds = $values['declared_vendor_ids'];
        $newCreative->setHtml($html);

        print "<h2>Creating Creative for '$parentName':</h2>";
        $result = $this->service->buyers_creatives->create($parentName, $newCreative);
        $this->printResult($result);
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Create Buyer HTML Creative';
    }
}

Python

#!/usr/bin/python
#
# Copyright 2020 Google Inc. All Rights Reserved.
#
# 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.

"""Creates a creative with HTML content for the given buyer account ID."""


import argparse
import datetime
import os
import pprint
import sys
import uuid

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError
import util


_BUYER_NAME_TEMPLATE = 'buyers/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'


def main(realtimebidding, args):
  account_id = args.account_id

  creative = {
    'advertiserName': args.advertiser_name,
    'creativeId': args.creative_id,
    'declaredAttributes': args.declared_attributes,
    'declaredClickThroughUrls': args.declared_click_urls,
    'declaredRestrictedCategories': args.declared_restricted_categories,
    'declaredVendorIds': [int(id) for id in args.declared_vendor_ids],
    'html': {
        'snippet': args.html_snippet,
        'height': args.html_height,
        'width': args.html_width
    }
  }

  print(f'Creating HTML creative for buyer account ID "{account_id}":')
  try:
    # Construct and execute the request.
    response = (realtimebidding.buyers().creatives().create(
        parent=_BUYER_NAME_TEMPLATE % account_id, body=creative).execute())
  except HttpError as e:
    print(e)
    sys.exit(1)

  pprint.pprint(response)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print(f'Unable to create realtimebidding service - {ex}')
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  default_snippet_content = (
      '<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 '
      'width=160 scrolling=no src=\"https://test.com/ads?id=123456'
      '&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%\"></iframe>')

  parser = argparse.ArgumentParser(
      description=('Creates an HTML creative for the given buyer account ID.'))

  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
      help=('The resource ID of the buyers resource under which the '
            'creative is to be created.'))
  # Optional fields.
  parser.add_argument(
      '--advertiser_name', default='Test',
      help='The name of the company being advertised in the creative.')
  parser.add_argument(
      '-c', '--creative_id', default='HTML_Creative_%s' % uuid.uuid4(),
      help=('The user-specified creative ID. The maximum length of the '
            'creative ID is 128 bytes.'))
  parser.add_argument(
      '--declared_attributes', nargs='*', default=['CREATIVE_TYPE_HTML'],
      help=('The creative attributes being declared. Specify each attribute '
            'separated by a space.'))
  parser.add_argument(
      '--declared_click_urls', nargs='*', default=['http://test.com'],
      help=('The click-through URLs being declared. Specify each URL '
            'separated by a space.'))
  parser.add_argument(
      '--declared_restricted_categories', nargs='*', default=[],
      help=('The restricted categories being declared. Specify each category '
            'separated by a space.'))
  parser.add_argument(
      '--declared_vendor_ids', nargs='*', default=[],
      help=('The vendor IDs being declared. Specify each ID separated by a '
            'space.'))
  parser.add_argument(
      '--html_snippet', default=default_snippet_content,
      help=('The HTML snippet that displays the ad when inserted in the '
            'web page.'))
  parser.add_argument(
      '--html_height', default=250,
      help='The height of the HTML snippet in pixels.')
  parser.add_argument(
      '--html_width', default=300,
      help='The width of the HTML snippet in pixels.')

  args = parser.parse_args()

  main(service, args)


Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2020 Google LLC
#
# License:: 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.
#
# Creates a creative with HTML content for the given buyer account ID.

require 'optparse'
require 'securerandom'

require_relative '../../../util'


def create_html_creatives(realtimebidding, options)  
  parent = "buyers/#{options[:account_id]}"

  body = Google::Apis::RealtimebiddingV1::Creative.new(
    advertiser_name: options[:advertiser_name],
    creative_id: options[:creative_id],
    declared_attributes: options[:declared_attributes],
    declared_click_through_urls: options[:declared_click_urls],
    declared_resricted_categories: options[:declared_restricted_categories],
    declared_vendor_ids: options[:declared_vendor_ids],
    html: Google::Apis::RealtimebiddingV1::HtmlContent.new(
      snippet: options[:html_snippet],
      height: options[:html_height],
      width: options[:html_width]
    )
  )

  puts "Creating HTML creative for buyer account '#{parent}'"

  creative = realtimebidding.create_buyer_creative(parent, creative_object=body)
  print_creative(creative)
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  default_snippet_content = <<~SNIPPET
    <iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 scrolling=no
        src="https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%">
    </iframe>
  SNIPPET

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the buyers resource under which the creatives were created, This will be used to construct '\
      'the name used as a path parameter for the creatives.get request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'creative_id', 'The user-specified creative ID. The maximum length of the creative ID is 128 bytes.',
      short_alias: 'c', required: false, default_value: "HTML_Creative_#{SecureRandom.uuid}"
    ),
    Option.new(
      'advertiser_name', 'The name of the company being advertised in the creative.', required: false,
      default_value: 'Test'
    ),
    Option.new(
      'declared_attributes', 'The creative attributes being declared. Specify each attribute separated by a comma.',
      required: false, type: Array, default_value: ['CREATIVE_TYPE_HTML']
    ),
    Option.new(
      'declared_click_urls', 'The click-through URLs being declared. Specify each URL separated by a comma.',
      required: false, type: Array, default_value: ['http://test.com']
    ),
    Option.new(
      'declared_restricted_categories',
      'The restricted categories being declared. Specify each category separated by a comma.',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'declared_vendor_ids', 'The vendor IDs being declared. Specify each ID separated by a space.',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'html_snippet', 'The HTML snippet that displays the ad when inserted in the web page.', required: false,
      default_value: default_snippet_content
    ),
    Option.new('html_height', 'The height of the HTML snippet in pixels.', required: false, default_value: 250),
    Option.new('html_width', 'The width of the HTML snippet in pixels.', required: false, default_value: 300),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    create_html_creatives(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

Submit a creative with native content for review

The following demonstrates how a simple creative with native content can be created and submitted for review with buyers.creatives.create.

REST

Request

POST https://realtimebidding.googleapis.com/v1/buyers/<INSERT_ACCOUNT_ID_HERE>/creatives?alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json
 
{
  "advertiserName": "Test",
  "creativeId": "Native_Creative_b7116b38-e9d4-4f63-a02a-3d27660730be",
  "declaredAttributes": [
    "NATIVE_ELIGIBILITY_ELIGIBLE"
  ],
  "declaredClickThroughUrls": [
    "http://test.com"
  ],
  "declaredRestrictedCategories": [],
  "declaredVendorIds": [],
  "native": {
    "headline": "Luxury Mars Cruises",
    "body": "Visit the planet in a luxury spaceship.",
    "callToAction": "Book today",
    "advertiserName": "Galactic Luxury Cruises",
    "image": {
      "url": "https://native.test.com/image?id=123456",
      "height": 627,
      "width": 1200
    },
    "logo": {
      "url": "https://native.test.com/logo?id=123456",
      "height": 100,
      "width": 100
    },
    "clickLinkUrl": "https://www.google.com",
    "clickTrackingUrl": "https://native.test.com/click?id=123456"
  }
}

Response

{
  "name": "buyers/<ACCOUNT_ID>/creatives/Native_Creative_b7116b38-e9d4-4f63-a02a-3d27660730be",
  "accountId": "<ACCOUNT_ID>",
  "creativeId": "Native_Creative_b7116b38-e9d4-4f63-a02a-3d27660730be",
  "native": {
    "headline": "Luxury Mars Cruises",
    "body": "Visit the planet in a luxury spaceship.",
    "callToAction": "Book today",
    "advertiserName": "Galactic Luxury Cruises",
    "image": {
      "url": "https://native.test.com/image?id=123456",
      "width": 1200,
      "height": 627
    },
    "logo": {
      "url": "https://native.test.com/logo?id=123456",
      "width": 100,
      "height": 100
    },
    "clickTrackingUrl": "https://native.test.com/click?id=123456",
    "clickLinkUrl": "https://www.google.com"
  },
  "creativeFormat": "NATIVE",
  "declaredClickThroughUrls": [
    "http://test.com"
  ],
  "declaredAttributes": [
    "NATIVE_ELIGIBILITY_ELIGIBLE"
  ],
  "advertiserName": "Test",
  "version": 1,
  "apiUpdateTime": "2020-08-06T23:55:19.967732Z",
  "creativeServingDecision": {
    "lastStatusUpdate": "2020-08-06T23:55:20.076Z",
    "dealsPolicyCompliance": {
      "status": "PENDING_REVIEW"
    },
    "networkPolicyCompliance": {
      "status": "PENDING_REVIEW"
    },
    "platformPolicyCompliance": {
      "status": "PENDING_REVIEW"
    },
    "chinaPolicyCompliance": {
      "status": "PENDING_REVIEW"
    },
    "russiaPolicyCompliance": {
      "status": "PENDING_REVIEW"
    }
  }
}

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.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Buyers.Creatives
{
    /// <summary>
    /// Creates a creative with native content for the given buyer account ID.
    /// </summary>
    public class CreateNativeCreatives : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public CreateNativeCreatives()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get { return "This code example creates a creative with native content for the " +
                         "given buyer account ID."; }
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            bool showHelp = false;

            string accountId = null;
            string advertiserName = null;
            string creativeId = null;
            IList<string> declaredAttributes = new List<string>();
            IList<string> declaredClickUrls = new List<string>();
            IList<string> declaredRestrictedCategories = new List<string>();
            IList<int?> declaredVendorIds = new List<int?>();
            string nativeHeadline = null;
            string nativeBody = null;
            string nativeCallToAction = null;
            string nativeAdvertiserName = null;
            string nativeImageUrl = null;
            int? nativeImageHeight = null;
            int? nativeImageWidth = null;
            string nativeLogoUrl = null;
            int? nativeLogoHeight = null;
            int? nativeLogoWidth = null;
            string nativeClickLinkUrl = null;
            string nativeClickTrackingUrl = null;

            OptionSet options = new OptionSet {
                "Creates a creative with native content for the given buyer account ID.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the buyers resource under which the " +
                     "creatives were created. This will be used to construct the name used as " +
                     "a path parameter for the creatives.get request."),
                    a => accountId = a
                },
                {
                    "advertiser_name=",
                    "The name of the company being advertised in the creative.",
                    advertiser_name => advertiserName = advertiser_name
                },
                {
                    "c|creative_id=",
                    ("The user-specified creative ID. The maximum length of the creative ID is " +
                     "128 bytes."),
                    c => creativeId = c
                },
                {
                    "declared_attributes=",
                    ("The creative attributes being declared. Specify this argument for each " +
                     "value you intend to include."),
                    declared_attributes => declaredAttributes.Add(declared_attributes)
                },
                {
                    "declared_click_urls=",
                    ("The click-through URLs being declared. Specify this argument for each " +
                     "value you intend to include."),
                    declared_click_through_urls => declaredClickUrls.Add(
                        declared_click_through_urls)
                },
                {
                    "declared_restricted_categories=",
                    ("The restricted categories being declared. Specify this argument for each " +
                     "value you intend to include."),
                    declared_restricted_categories => declaredRestrictedCategories.Add(
                        declared_restricted_categories)
                },
                {
                    "declared_vendor_ids=",
                    ("The vendor IDs being declared. Specify this argument for each value you " +
                     "intend to include."),
                    (int declared_vendor_ids) => declaredVendorIds.Add(declared_vendor_ids)
                },
                {
                    "native_headline=",
                    "A short title for the ad.",
                    native_headline => nativeHeadline = native_headline
                },
                {
                    "native_body=",
                    "A long description of the ad.",
                    native_body => nativeBody = native_body
                },
                {
                    "native_call_to_action=",
                    "A label for the button that the user is supposed to click.",
                    native_call_to_action => nativeCallToAction = native_call_to_action
                },
                {
                    "native_advertiser_name=",
                    "The name of the advertiser or sponsor, to be displayed in the ad creative.",
                    native_advertiser_name => nativeAdvertiserName = native_advertiser_name
                },
                {
                    "native_image_url=",
                    "The URL of the large image to be included in the native ad.",
                    native_image_url => nativeImageUrl = native_image_url
                },
                {
                    "native_image_height=",
                    "The height in pixels of the native ad's large image.",
                    (int native_image_height) => nativeImageHeight = native_image_height
                },
                {
                    "native_image_width=",
                    "The width in pixels of the native ad's large image.",
                    (int native_image_width) => nativeImageWidth = native_image_width
                },
                {
                    "native_logo_url=",
                    "The URL of a smaller image to be included in the native ad.",
                    native_logo_url => nativeLogoUrl = native_logo_url
                },
                {
                    "native_logo_height=",
                    "The height in pixels of the native ad's smaller image.",
                    (int native_logo_height) => nativeLogoHeight = native_logo_height
                },
                {
                    "native_logo_width=",
                    "The height in pixels of the native ad's smaller image.",
                    (int native_logo_width) => nativeLogoWidth = native_logo_width
                },
                {
                    "native_click_link_url=",
                    "The URL that the browser/SDK will load when the user clicks the ad.",
                    native_click_link_url => nativeClickLinkUrl = native_click_link_url
                },
                {
                    "native_click_tracking_url=",
                    "The URL to use for click tracking.",
                    native_click_tracking_url => nativeClickTrackingUrl = native_click_tracking_url
                },
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Handle error conditions.
            if(extras.Count > 0)
            {
                Console.Error.WriteLine("Unknown arguments specified:");
                foreach(string arg in extras)
                {
                    Console.Error.WriteLine(arg);
                }
                Environment.Exit(1);
            }
            // Verify required arguments were set.
            if(accountId == null)
            {
                Console.Error.WriteLine("Required argument \"account_id\" not specified.");
                options.WriteOptionDescriptions(Console.Error);
                Environment.Exit(1);
            }
            else
            {
                parsedArgs["accountId"] = accountId;
            }

            // Set optional arguments.
            parsedArgs["advertiser_name"] = advertiserName ?? "Test";
            parsedArgs["creative_id"] = creativeId ?? String.Format(
                "Native_Creative_{0}", System.Guid.NewGuid());

            if (declaredAttributes.Count == 0)
            {
                declaredAttributes.Add("NATIVE_ELIGIBILITY_ELIGIBLE");
            }
            parsedArgs["declared_attributes"] = declaredAttributes;

            if (declaredClickUrls.Count == 0)
            {
                declaredClickUrls.Add("http://test.com");
            }

            parsedArgs["declared_click_urls"] = declaredClickUrls;
            parsedArgs["declared_restricted_categories"] = declaredRestrictedCategories;
            parsedArgs["declared_vendor_ids"] = declaredVendorIds;
            parsedArgs["native_headline"] = nativeHeadline ?? "Luxury Mars Cruises";
            parsedArgs["native_body"] = nativeBody ?? "Visit the planet in a luxury spaceship.";
            parsedArgs["native_call_to_action"] = nativeHeadline ?? "Book today";
            parsedArgs["native_advertiser_name"] =
                nativeAdvertiserName ?? "Galactic Luxury Cruises";
            parsedArgs["native_image_url"] =
                nativeImageUrl ?? "https://native.test.com/image?id=123456";
            parsedArgs["native_image_height"] = nativeImageHeight ?? 627;
            parsedArgs["native_image_width"] = nativeImageWidth ?? 1200;
            parsedArgs["native_image_url"] = "https://native.test.com/image?id=123456";
            parsedArgs["native_image_height"] = 627;
            parsedArgs["native_image_width"] = 1200;
            parsedArgs["native_logo_url"] =
                nativeLogoUrl ?? "https://native.test.com/logo?id=123456";
            parsedArgs["native_logo_height"] = nativeLogoHeight ?? 100;
            parsedArgs["native_logo_width"] = nativeLogoWidth ?? 100;
            parsedArgs["native_click_link_url"] = nativeClickLinkUrl ?? "https://www.google.com";
            parsedArgs["native_click_tracking_url"] =
                nativeClickTrackingUrl ?? "https://native.test.com/click?id=123456";

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            string accountId = (string) parsedArgs["accountId"];
            string parent = $"buyers/{accountId}";

            Image nativeImage = new Image();
            nativeImage.Url = (string) parsedArgs["native_image_url"];
            nativeImage.Height = (int?) parsedArgs["native_image_height"];
            nativeImage.Width = (int?) parsedArgs["native_image_width"];

            Image nativeLogo = new Image();
            nativeLogo.Url = (string) parsedArgs["native_logo_url"];
            nativeLogo.Height = (int?) parsedArgs["native_logo_height"];
            nativeLogo.Width = (int?) parsedArgs["native_logo_width"];

            NativeContent nativeContent = new NativeContent();
            nativeContent.Headline = (string) parsedArgs["native_headline"];
            nativeContent.Body = (string) parsedArgs["native_body"];
            nativeContent.CallToAction = (string) parsedArgs["native_call_to_action"];
            nativeContent.AdvertiserName = (string) parsedArgs["native_advertiser_name"];
            nativeContent.Image = nativeImage;
            nativeContent.Logo = nativeLogo;
            nativeContent.ClickLinkUrl = (string) parsedArgs["native_click_link_url"];
            nativeContent.ClickTrackingUrl = (string) parsedArgs["native_click_tracking_url"];

            Creative newCreative = new Creative();
            newCreative.AdvertiserName = (string) parsedArgs["advertiser_name"];
            newCreative.CreativeId = (string) parsedArgs["creative_id"];
            newCreative.DeclaredAttributes = (IList<string>) parsedArgs["declared_attributes"];
            newCreative.DeclaredClickThroughUrls = (IList<string>) parsedArgs[
                "declared_click_urls"];
            newCreative.DeclaredRestrictedCategories = (IList<string>) parsedArgs[
                "declared_restricted_categories"];
            newCreative.DeclaredVendorIds = (IList<int?>) parsedArgs["declared_vendor_ids"];
            newCreative.Native = nativeContent;

            BuyersResource.CreativesResource.CreateRequest request =
                rtbService.Buyers.Creatives.Create(newCreative, parent);
            Creative response = null;

            Console.WriteLine("Creating native creative for buyer: {0}", parent);

            try
            {
                response = request.Execute();
            }
            catch (System.Exception exception)
            {
                Console.Error.WriteLine("Real-time Bidding API returned error response:\n{0}",
                                        exception.Message);
                Environment.Exit(1);
            }

            Utilities.PrintCreative(response);
        }
    }
}

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.api.services.samples.authorizedbuyers.realtimebidding.v1.buyers.creatives;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.Creative;
import com.google.api.services.realtimebidding.v1.model.Image;
import com.google.api.services.realtimebidding.v1.model.NativeContent;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.UUID;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/**
 * Creates a creative with native content for the given buyer account ID.
 */
public class CreateNativeCreatives {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) {
    Integer accountId = parsedArgs.getInt("account_id");

    String parentBuyerName = String.format("buyers/%s", accountId);

    Image image = new Image();
    image.setUrl(parsedArgs.getString("native_image_url"));
    image.setHeight(parsedArgs.getInt("native_image_height"));
    image.setWidth(parsedArgs.getInt("native_image_width"));

    Image logo = new Image();
    logo.setUrl(parsedArgs.getString("native_logo_url"));
    logo.setHeight(parsedArgs.getInt("native_logo_height"));
    logo.setWidth(parsedArgs.getInt("native_logo_width"));

    NativeContent nativeContent = new NativeContent();
    nativeContent.setHeadline(parsedArgs.getString("native_headline"));
    nativeContent.setBody(parsedArgs.getString("native_body"));
    nativeContent.setCallToAction(parsedArgs.getString("native_call_to_action"));
    nativeContent.setAdvertiserName(parsedArgs.getString("native_advertiser_name"));
    nativeContent.setImage(image);
    nativeContent.setLogo(logo);
    nativeContent.setClickLinkUrl(parsedArgs.getString("native_click_link_url"));
    nativeContent.setClickTrackingUrl(parsedArgs.getString("native_click_tracking_url"));

    Creative newCreative = new Creative();
    newCreative.setAdvertiserName(parsedArgs.getString("advertiser_name"));
    newCreative.setCreativeId(parsedArgs.getString("creative_id"));
    newCreative.setDeclaredAttributes(parsedArgs.<String>getList("declared_attributes"));
    newCreative.setDeclaredClickThroughUrls(parsedArgs.<String>getList("declared_click_urls"));
    newCreative.setDeclaredRestrictedCategories(parsedArgs.<String>getList(
        "declared_restricted_categories"));
    newCreative.setDeclaredVendorIds(parsedArgs.<Integer>getList("declared_vendor_ids"));
    newCreative.setNative(nativeContent);

    Creative creative = null;
    try {
      creative = client.buyers().creatives().create(parentBuyerName, newCreative).execute();
    } catch(IOException ex) {
    System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
    System.exit(1);
  }

    System.out.printf("Created creative for buyer Account ID '%s':\n", accountId);
    Utils.printCreative(creative);
  }

  public static void main(String[] args) {
    ArgumentParser parser = ArgumentParsers.newFor("CreateNativeCreatives").build()
        .defaultHelp(true)
        .description(("Creates an native creative for the given buyer account ID."));
    parser.addArgument("-a", "--account_id")
        .help("The resource ID of the buyers resource under which the creative is to be created. ")
        .required(true)
        .type(Integer.class);
    parser.addArgument("--advertiser_name")
        .help("The name of the company being advertised in the creative.")
        .setDefault("Test");
    parser.addArgument("-c", "--creative_id")
        .help("The user-specified creative ID. The maximum length of the creative ID is 128 bytes.")
        .setDefault(String.format("Native_Creative_%s", UUID.randomUUID()));
    parser.addArgument("--declared_attributes")
        .help("The creative attributes being declared. Specify each attribute separated by a " +
            "space.")
        .nargs("*")
        .setDefault(Collections.singletonList("NATIVE_ELIGIBILITY_ELIGIBLE"));
    parser.addArgument("--declared_click_urls")
        .help("The click-through URLs being declared. Specify each URL separated by a space.")
        .nargs("*")
        .setDefault(Collections.singletonList("http://test.com"));
    parser.addArgument("--declared_restricted_categories")
        .help("The restricted categories being declared. Specify each category separated by a " +
            "space.")
        .nargs("*");
    parser.addArgument("--declared_vendor_ids")
        .help("The vendor IDs being declared. Specify each ID separated by a space.")
        .type(Integer.class)
        .nargs("*");
    parser.addArgument("--native_headline")
        .help("A short title for the ad.")
        .setDefault("Luxury Mars Cruises");
    parser.addArgument("--native_body")
        .help("A long description of the ad.")
        .setDefault("Visit the planet in a luxury spaceship.");
    parser.addArgument("--native_call_to_action")
        .help("A label for the button that the user is supposed to click.")
        .setDefault("Book today");
    parser.addArgument("--native_advertiser_name")
        .help("The name of the advertiser or sponsor, to be displayed in the ad creative.")
        .setDefault("Galactic Luxury Cruises");
    parser.addArgument("--native_image_url")
        .help("The URL of the large image to be included in the native ad.")
        .setDefault("https://native.test.com/image?id=123456");
    parser.addArgument("--native_image_height")
        .help("The height in pixels of the native ad's large image.")
        .type(Integer.class)
        .setDefault(627);
    parser.addArgument("--native_image_width")
        .help("The width in pixels of the native ad's large image.")
        .type(Integer.class)
        .setDefault(1200);
    parser.addArgument("--native_logo_url")
        .help("The URL of a smaller image to be included in the native ad.")
        .setDefault("https://native.test.com/logo?id=123456");
    parser.addArgument("--native_logo_height")
        .help("The height in pixels of the native ad's smaller image.")
        .type(Integer.class)
        .setDefault(100);
    parser.addArgument("--native_logo_width")
        .help("The width in pixels of the native ad's smaller image.")
        .type(Integer.class)
        .setDefault(100);
    parser.addArgument("--native_click_link_url")
        .help("The URL that the browser/SDK will load when the user clicks the ad.")
        .setDefault("https://www.google.com");
    parser.addArgument("--native_click_tracking_url")
        .help("The URL to use for click tracking.")
        .setDefault("https://native.test.com/click?id=123456");

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:\n%s", ex);
      System.exit(1);
    }

    execute(client, parsedArgs);
  }
}

PHP

<?php

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

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Buyers_Creatives;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;
use Google_Service_RealTimeBidding_Creative;
use Google_Service_RealTimeBidding_Image;
use Google_Service_RealTimeBidding_NativeContent;

/**
 * This example illustrates how to create native creatives for a given buyer account.
 */
class CreateNativeCreatives extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Account ID',
                'description' =>
                    'The resource ID of the buyers resource under which the creative is to be ' .
                    'created.',
                'required' => true
            ],
            [
                'name' => 'advertiser_name',
                'display' => 'Advertiser name',
                'description' => 'The name of the company being advertised in the creative.',
                'required' => false,
                'default' => 'Test'
            ],
            [
                'name' => 'creative_id',
                'display' => 'Creative ID',
                'description' =>
                    'The user-specified creative ID. The maximum length of the creative ID is ' .
                    '128 bytes',
                'required' => false,
                'default' => 'Native_Creative_' . uniqid()
            ],
            [
                'name' => 'declared_attributes',
                'display' => 'Declared attributes',
                'description' =>
                    'The creative attributes being declared. Specify each attribute separated ' .
                    'by a comma.',
                'required' => false,
                'is_array' => true,
                'default' => ['NATIVE_ELIGIBILITY_ELIGIBLE']
            ],
            [
                'name' => 'declared_click_urls',
                'display' => 'Declared click URLs',
                'description' =>
                    'The click-through URLs being declared. Specify each URL separated by a ' .
                    'comma.',
                'required' => false,
                'is_array' => true,
                'default' => ['http://test.com']
            ],
            [
                'name' => 'declared_restricted_categories',
                'display' => 'Declared restricted categories',
                'description' =>
                    'The restricted categories being declared. Specify each category separated ' .
                    'by a comma.',
                'required' => false,
                'is_array' => true
            ],
            [
                'name' => 'declared_vendor_ids',
                'display' => 'Declared vendor IDs',
                'description' =>
                    'The vendor IDs being declared. Specify each ID separated by a comma.',
                'required' => false,
                'is_array' => true
            ],
            [
                'name' => 'native_headline',
                'display' => 'Native ad headline',
                'description' => 'A short title for the ad.',
                'required' => false,
                'default' => 'Luxury Mars Cruises'
            ],
            [
                'name' => 'native_body',
                'display' => 'Native ad body',
                'description' => 'A long description of the ad.',
                'required' => false,
                'default' => 'Visit the planet in a luxury spaceship.'
            ],
            [
                'name' => 'native_call_to_action',
                'display' => 'Native ad call to action',
                'description' => 'A label for the button that the user is supposed to click.',
                'required' => false,
                'default' => 'Book today'
            ],
            [
                'name' => 'native_advertiser_name',
                'display' => 'Native ad advertiser name',
                'description' =>
                    'The name of the advertiser or sponsor, to be displayed in the ad creative.',
                'required' => false,
                'default' => 'Galactic Luxury Cruises'
            ],
            [
                'name' => 'native_image_url',
                'display' => 'Native ad image url',
                'description' => 'The URL of the large image to be included in the native ad.',
                'required' => false,
                'default' => 'https://native.test.com/image?id=123456'
            ],
            [
                'name' => 'native_image_height',
                'display' => 'Native ad image height',
                'description' => 'The height in pixels of the native ad\'s large image.',
                'required' => false,
                'default' => 627
            ],
            [
                'name' => 'native_image_width',
                'display' => 'Native ad image width',
                'description' => 'The width in pixels of the native ad\'s large image.',
                'required' => false,
                'default' => 1200
            ],
            [
                'name' => 'native_logo_url',
                'display' => 'Native ad logo url',
                'description' => 'The URL of a smaller image to be included in the native ad.',
                'required' => false,
                'default' => 'https://native.test.com/logo?id=123456'
            ],
            [
                'name' => 'native_logo_height',
                'display' => 'Native ad logo height',
                'description' => 'The height in pixels of the native ad\'s smaller image.',
                'required' => false,
                'default' => 100
            ],
            [
                'name' => 'native_logo_width',
                'display' => 'Native ad logo width',
                'description' => 'The width in pixels of the native ad\'s smaller image.',
                'required' => false,
                'default' => 100
            ],
            [
                'name' => 'native_click_link_url',
                'display' => 'Native ad click link URL',
                'description' =>
                    'The URL that the browser/SDK will load when the user clicks ' .
                    'the ad.',
                'required' => false,
                'default' => 'https://www.google.com'
            ],
            [
                'name' => 'native_click_tracking_url',
                'display' => 'Native ad click tracking URL',
                'description' => 'The URL to use for click tracking.',
                'required' => false,
                'default' => 'https://native.test.com/click?id=123456'
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;
        $parentName = "buyers/$values[account_id]";

        $image = new Google_Service_RealTimeBidding_Image();
        $image->url = $values['native_image_url'];
        $image->height = $values['native_image_height'];
        $image->width = $values['native_image_width'];

        $logo = new Google_Service_RealTimeBidding_Image();
        $logo->url = $values['native_logo_url'];
        $logo->height = $values['native_logo_height'];
        $logo->width = $values['native_logo_width'];

        $native = new Google_Service_RealTimeBidding_NativeContent();
        $native->headline = $values['native_headline'];
        $native->body = $values['native_body'];
        $native->callToAction = $values['native_call_to_action'];
        $native->advertiserName = $values['native_advertiser_name'];
        $native->setImage($image);
        $native->setLogo($logo);

        $newCreative = new Google_Service_RealTimeBidding_Creative();
        $newCreative->advertiserName = $values['advertiser_name'];
        $newCreative->creativeId = $values['creative_id'];
        $newCreative->declaredAttributes = $values['declared_attributes'];
        $newCreative->declaredClickThroughUrls = $values['declared_click_urls'];
        $newCreative->declaredRestrictedCategories = $values['declared_restricted_categories'];
        $newCreative->declaredVendorIds = $values['declared_vendor_ids'];
        $newCreative->setNative($native);

        print "<h2>Creating Creative for '$parentName':</h2>";
        $result = $this->service->buyers_creatives->create($parentName, $newCreative);
        $this->printResult($result);
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Create Buyer Native Creative';
    }
}

Python

#!/usr/bin/python
#
# Copyright 2020 Google Inc. All Rights Reserved.
#
# 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.

"""Creates a creative with native content for the given buyer account ID."""


import argparse
import datetime
import os
import pprint
import sys
import uuid

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError
import util


_BUYER_NAME_TEMPLATE = 'buyers/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'


def main(realtimebidding, args):
  account_id = args.account_id

  creative = {
    'advertiserName': args.advertiser_name,
    'creativeId': args.creative_id,
    'declaredAttributes': args.declared_attributes,
    'declaredClickThroughUrls': args.declared_click_urls,
    'declaredRestrictedCategories': args.declared_restricted_categories,
    'declaredVendorIds': [int(id) for id in args.declared_vendor_ids],
    'native': {
        'headline': args.native_headline,
        'body': args.native_body,
        'callToAction': args.native_call_to_action,
        'advertiserName': args.native_advertiser_name,
        'image': {
            'url': args.native_image_url,
            'height': args.native_image_height,
            'width': args.native_image_width
        },
        'logo': {
            'url': args.native_logo_url,
            'height': args.native_logo_height,
            'width': args.native_logo_width
        },
        'clickLinkUrl': args.native_click_link_url,
        'clickTrackingUrl': args.native_click_tracking_url
    }
  }

  print(f'Creating native creative for buyer account ID "{account_id}":')
  try:
    # Construct and execute the request.
    response = (realtimebidding.buyers().creatives().create(
        parent=_BUYER_NAME_TEMPLATE % account_id, body=creative).execute())
  except HttpError as e:
    print(e)
    sys.exit(1)

  pprint.pprint(response)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print(f'Unable to create realtimebidding service - {ex}')
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Creates a native creative for the given buyer account ID.')
  )

  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
      help=('The resource ID of the buyers resource under which the '
            'creative is to be created.'))
  # Optional fields.
  parser.add_argument(
      '--advertiser_name', default='Test',
      help='The name of the company being advertised in the creative.')
  parser.add_argument(
      '-c', '--creative_id', default='Native_Creative_%s' % uuid.uuid4(),
      help=('The user-specified creative ID. The maximum length of the '
            'creative ID is 128 bytes.'))
  parser.add_argument(
      '--declared_attributes', nargs='*',
      default=['NATIVE_ELIGIBILITY_ELIGIBLE'],
      help=('The creative attributes being declared. Specify each attribute '
            'separated by a space.'))
  parser.add_argument(
      '--declared_click_urls', nargs='*', default=['http://test.com'],
      help=('The click-through URLs being declared. Specify each URL '
            'separated by a space.'))
  parser.add_argument(
      '--declared_restricted_categories', nargs='*', default=[],
      help=('The restricted categories being declared. Specify each category '
            'separated by a space.'))
  parser.add_argument(
      '--declared_vendor_ids', nargs='*', default=[],
      help=('The vendor IDs being declared. Specify each ID separated by a '
            'space.'))
  parser.add_argument(
      '--native_headline', default='Luxury Mars Cruises',
      help=('A short title for the ad.'))
  parser.add_argument(
      '--native_body', default='Visit the planet in a luxury spaceship.',
      help='A long description of the ad.'),
  parser.add_argument(
      '--native_call_to_action', default='Book today',
      help='A label for the button that the user is supposed to click.')
  parser.add_argument(
      '--native_advertiser_name', default='Galactic Luxury Cruises',
      help=('The name of the advertiser or sponsor, to be displayed in the ad '
            'creative.')),
  parser.add_argument(
      '--native_image_url', default='https://native.test.com/image?id=123456',
      help='The URL of the large image to be included in the native ad.'),
  parser.add_argument(
      '--native_image_height', default=627,
      help='The height in pixels of the native ad\'s large image.'),
  parser.add_argument(
      '--native_image_width', default=1200,
      help='The width in pixels of the native ad\'s large image.'),
  parser.add_argument(
      '--native_logo_url', default='https://native.test.com/logo?id=123456',
      help='The URL of a smaller image to be included in the native ad.'),
  parser.add_argument(
      '--native_logo_height', default=100,
      help='The height in pixels of the native ad\'s smaller image.'),
  parser.add_argument(
      '--native_logo_width', default=100,
      help='The width in pixels of the native ad\'s smaller image.'),
  parser.add_argument(
      '--native_click_link_url', default='https://www.google.com',
      help=('The URL that the browser/SDK will load when the user clicks the '
           'ad.')),
  parser.add_argument(
      '--native_click_tracking_url',
      default='https://native.test.com/click?id=123456',
      help='The URL to use for click tracking.'),

  args = parser.parse_args()

  main(service, args)


Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2020 Google LLC
#
# License:: 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.
#
# Creates a creative with native content for the given buyer account ID.

require 'optparse'
require 'securerandom'

require_relative '../../../util'


def create_native_creatives(realtimebidding, options)
  parent = "buyers/#{options[:account_id]}"

  body = Google::Apis::RealtimebiddingV1::Creative.new(
      advertiser_name: options[:advertiser_name],
      creative_id: options[:creative_id],
      declared_attributes: options[:declared_attributes],
      declared_click_through_urls: options[:declared_click_urls],
      declared_resricted_categories: options[:declared_restricted_categories],
      declared_vendor_ids: options[:declared_vendor_ids],
      native: Google::Apis::RealtimebiddingV1::NativeContent.new(
          headline: options[:native_headline],
          body: options[:native_body],
          call_to_action: options[:native_call_to_action],
          advertiser_name: options[:native_advertiser_name],
          image: Google::Apis::RealtimebiddingV1::Image.new(
              url: options[:native_image_url],
              height: options[:native_image_height],
              width: options[:native_image_width]
          ),
          logo: Google::Apis::RealtimebiddingV1::Image.new(
              url: options[:native_logo_url],
              height: options[:native_logo_height],
              width: options[:native_logo_width]
          ),
          click_link_url: options[:native_click_link_url],
          click_tracking_url: options[:native_click_tracking_url]
      )
  )

  puts "Creating native creative for buyer account '#{parent}'"

  creative = realtimebidding.create_buyer_creative(parent, creative_object=body)
  print_creative(creative)
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the buyers resource under which the creatives were created, This will be used to construct '\
      'the name used as a path parameter for the creatives.get request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'creative_id',
      'The user-specified creative ID. The maximum length of the creative ID is 128 bytes.',
      short_alias: 'c', required: false, default_value: "Native_Creative_#{SecureRandom.uuid}"
    ),
    Option.new(
      'advertiser_name', 'The name of the company being advertised in the creative.', required: false,
      default_value: 'Test'
    ),
    Option.new(
      'declared_attributes', 'The creative attributes being declared. Specify each attribute separated by a comma.',
      required: false, type: Array, default_value: ['NATIVE_ELIGIBILITY_ELIGIBLE']
    ),
    Option.new(
      'declared_click_urls', 'The click-through URLs being declared. Specify each URL separated by a comma.',
      required: false, type: Array, default_value: ['http://test.com']
    ),
    Option.new(
      'declared_restricted_categories',
      'The restricted categories being declared. Specify each category separated by a comma.',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'declared_vendor_ids', 'The vendor IDs being declared. Specify each ID separated by a space.',
      required: false, type: Array, default_value: []
    ),
    Option.new('native_headline', 'A short title for the ad.', required: false, default_value: 'Luxury Mars Cruises'),
    Option.new(
      'native_body', 'A long description of the ad.', required: false,
      default_value: 'Visit the planet in a luxury spaceship.'
    ),
    Option.new(
      'native_call_to_action', 'A label for the button that the user is supposed to click.', required: false,
      default_value: 'Book today'
    ),
    Option.new(
      'native_advertiser_name', 'The name of the advertiser or sponsor, to be displayed in the ad creative',
      required: false, default_value: 'Galactic Luxury Cruises'
    ),
    Option.new(
      'native_image_url', 'The URL of the large image to be included in the native ad.', required: false,
      default_value: 'https://native.test.com/image?id=123456'
    ),
    Option.new(
      'native_image_height', 'The height in pixels of the native ad\'s large image.', required: false,
      default_value: 627
    ),
    Option.new(
      'native_image_width', 'The width in pixels of the native ad\'s large image.', required: false,
      default_value: 1200
    ),
    Option.new(
      'native_logo_url', 'The URL of a smaller image to be included in the native ad.', required: false,
      default_value: 'https://native.test.com/logo?id=123456'
    ),
    Option.new(
      'native_logo_height', 'The height in pixels of the native ad\'s smaller image.', required: false,
      default_value: 100
    ),
    Option.new(
      'native_logo_width', 'The width in pixels of the native ad\'s smaller image.', required: false,
      default_value: 100
    ),
    Option.new(
      'native_click_link_url', 'The URL that the browser/SDK will load when the user clicks the ad.', required: false,
      default_value: 'https://www.google.com'
    ),
    Option.new(
      'native_click_tracking_url', 'The URL to use for click tracking.', required: false,
      default_value: 'https://native.test.com/click?id=123456'
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    create_native_creatives(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

Submit a creative with video content for review

The following demonstrates how a simple creative with video content can be created and submitted for review with buyers.creatives.create.

REST

Request

POST https://realtimebidding.googleapis.com/v1/buyers/<INSERT_ACCOUNT_ID_HERE>/creatives?alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json
 
{
  "advertiserName": "Test",
  "creativeId": "HTML_Creative_87b8902b-51ad-421a-849a-a064e1b4c6e3",
  "declaredAttributes": [
    "CREATIVE_TYPE_VAST_VIDEO"
  ],
  "declaredClickThroughUrls": [
    "http://test.com"
  ],
  "declaredRestrictedCategories": [],
  "declaredVendorIds": [],
  "video": {
    "videoUrl": "https://video.test.com/ads?id=123456&wprice=%%WINNING_PRICE%%"
  }
}

Response

{
  "name": "buyers/<ACCOUNT_ID>/creatives/HTML_Creative_87b8902b-51ad-421a-849a-a064e1b4c6e3",
  "accountId": "<ACCOUNT_ID>",
  "creativeId": "HTML_Creative_87b8902b-51ad-421a-849a-a064e1b4c6e3",
  "video": {
    "videoUrl": "https://video.test.com/ads?id=123456&wprice=%%WINNING_PRICE%%"
  },
  "creativeFormat": "VIDEO",
  "declaredClickThroughUrls": [
    "http://test.com"
  ],
  "declaredAttributes": [
    "CREATIVE_TYPE_VAST_VIDEO"
  ],
  "advertiserName": "Test",
  "version": 1,
  "apiUpdateTime": "2020-08-06T23:59:58.554262Z",
  "creativeServingDecision": {
    "lastStatusUpdate": "2020-08-06T23:59:58.555Z",
    "dealsPolicyCompliance": {
      "status": "PENDING_REVIEW"
    },
    "networkPolicyCompliance": {
      "status": "PENDING_REVIEW"
    },
    "platformPolicyCompliance": {
      "status": "PENDING_REVIEW"
    },
    "chinaPolicyCompliance": {
      "status": "PENDING_REVIEW"
    },
    "russiaPolicyCompliance": {
      "status": "PENDING_REVIEW"
    }
  }
}

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.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Buyers.Creatives
{
    /// <summary>
    /// Creates a creative with video content for the given buyer account ID.
    /// </summary>
    public class CreateVideoCreatives : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public CreateVideoCreatives()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get { return "This code example creates a creative with video content for the " +
                         "given buyer account ID."; }
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            bool showHelp = false;

            string accountId = null;
            string advertiserName = null;
            string creativeId = null;
            IList<string> declaredAttributes = new List<string>();
            IList<string> declaredClickUrls = new List<string>();
            IList<string> declaredRestrictedCategories = new List<string>();
            IList<int?> declaredVendorIds = new List<int?>();
            string videoUrl = null;

            var defaultVideoUrl = "https://video.test.com/ads?id=123456&wprice=%%WINNING_PRICE%%";

            OptionSet options = new OptionSet {
                "Creates a creative with video content for the given buyer account ID.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the buyers resource under which the " +
                     "creatives were created. This will be used to construct the name used as " +
                     "a path parameter for the creatives.get request."),
                    a => accountId = a
                },
                {
                    "advertiser_name=",
                    "The name of the company being advertised in the creative.",
                    advertiser_name => advertiserName = advertiser_name
                },
                {
                    "c|creative_id=",
                    ("The user-specified creative ID. The maximum length of the creative ID is " +
                     "128 bytes."),
                    c => creativeId = c
                },
                {
                    "declared_attributes=",
                    ("The creative attributes being declared. Specify this argument for each " +
                     "value you intend to include."),
                    declared_attributes => declaredAttributes.Add(declared_attributes)
                },
                {
                    "declared_click_urls=",
                    ("The click-through URLs being declared. Specify this argument for each " +
                     "value you intend to include."),
                    declared_click_through_urls => declaredClickUrls.Add(
                        declared_click_through_urls)
                },
                {
                    "declared_restricted_categories=",
                    ("The restricted categories being declared. Specify this argument for each " +
                     "value you intend to include."),
                    declared_restricted_categories => declaredRestrictedCategories.Add(
                        declared_restricted_categories)
                },
                {
                    "declared_vendor_ids=",
                    ("The vendor IDs being declared. Specify this argument for each value you " +
                     "intend to include."),
                    (int declared_vendor_ids) => declaredVendorIds.Add(declared_vendor_ids)
                },
                {
                    "video_url=",
                    "The URL used to fetch a video ad.",
                    video_url => videoUrl = video_url
                }
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Handle error conditions.
            if(extras.Count > 0)
            {
                Console.Error.WriteLine("Unknown arguments specified:");
                foreach(string arg in extras)
                {
                    Console.Error.WriteLine(arg);
                }
                Environment.Exit(1);
            }
            // Verify required arguments were set.
            if(accountId == null)
            {
                Console.Error.WriteLine("Required argument \"account_id\" not specified.");
                options.WriteOptionDescriptions(Console.Error);
                Environment.Exit(1);
            }
            else
            {
                parsedArgs["accountId"] = accountId;
            }

            // Set optional arguments.
            parsedArgs["advertiser_name"] = advertiserName ?? "Test";
            parsedArgs["creative_id"] = creativeId ?? String.Format(
                "Video_Creative_{0}", System.Guid.NewGuid());

            if (declaredAttributes.Count == 0)
            {
                declaredAttributes.Add("CREATIVE_TYPE_VAST_VIDEO");
            }
            parsedArgs["declared_attributes"] = declaredAttributes;

            if (declaredClickUrls.Count == 0)
            {
                declaredClickUrls.Add("http://test.com");
            }

            parsedArgs["declared_click_urls"] = declaredClickUrls;
            parsedArgs["declared_restricted_categories"] = declaredRestrictedCategories;
            parsedArgs["declared_vendor_ids"] = declaredVendorIds;
            parsedArgs["video_url"] = videoUrl ?? defaultVideoUrl;

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            string accountId = (string) parsedArgs["accountId"];
            string parent = $"buyers/{accountId}";

            VideoContent videoContent = new VideoContent();
            videoContent.VideoUrl = (string) parsedArgs["video_url"];

            Creative newCreative = new Creative();
            newCreative.AdvertiserName = (string) parsedArgs["advertiser_name"];
            newCreative.CreativeId = (string) parsedArgs["creative_id"];
            newCreative.DeclaredAttributes = (IList<string>) parsedArgs["declared_attributes"];
            newCreative.DeclaredClickThroughUrls = (IList<string>) parsedArgs[
                "declared_click_urls"];
            newCreative.DeclaredRestrictedCategories = (IList<string>) parsedArgs[
                "declared_restricted_categories"];
            newCreative.DeclaredVendorIds = (IList<int?>) parsedArgs["declared_vendor_ids"];
            newCreative.Video = videoContent;

            BuyersResource.CreativesResource.CreateRequest request =
                rtbService.Buyers.Creatives.Create(newCreative, parent);
            Creative response = null;

            Console.WriteLine("Creating video creative for buyer: {0}", parent);

            try
            {
                response = request.Execute();
            }
            catch (System.Exception exception)
            {
                Console.Error.WriteLine("Real-time Bidding API returned error response:\n{0}",
                                        exception.Message);
                Environment.Exit(1);
            }

            Utilities.PrintCreative(response);
        }
    }
}

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.api.services.samples.authorizedbuyers.realtimebidding.v1.buyers.creatives;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.Creative;
import com.google.api.services.realtimebidding.v1.model.VideoContent;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.UUID;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/**
 * Creates a creative with video content for the given buyer account ID.
 */
public class CreateVideoCreatives {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) {
    Integer accountId = parsedArgs.getInt("account_id");

    String parentBuyerName = String.format("buyers/%s", accountId);

    VideoContent videoContent = new VideoContent();
    videoContent.setVideoUrl(parsedArgs.getString("video_url"));

    Creative newCreative = new Creative();
    newCreative.setAdvertiserName(parsedArgs.getString("advertiser_name"));
    newCreative.setCreativeId(parsedArgs.getString("creative_id"));
    newCreative.setDeclaredAttributes(parsedArgs.<String>getList("declared_attributes"));
    newCreative.setDeclaredClickThroughUrls(parsedArgs.<String>getList("declared_click_urls"));
    newCreative.setDeclaredRestrictedCategories(parsedArgs.<String>getList("declared_restricted_categories"));
    newCreative.setDeclaredVendorIds(parsedArgs.<Integer>getList("declared_vendor_ids"));
    newCreative.setVideo(videoContent);

    Creative creative = null;
    try {
      creative = client.buyers().creatives().create(parentBuyerName, newCreative).execute();
    } catch(IOException ex) {
    System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
    System.exit(1);
  }

    System.out.printf("Created creative for buyer Account ID '%s':\n", accountId);
    Utils.printCreative(creative);
  }

  public static void main(String[] args) {
    ArgumentParser parser = ArgumentParsers.newFor("CreateVideoCreatives").build()
        .defaultHelp(true)
        .description(("Creates a video creative for the given buyer account ID."));
    parser.addArgument("-a", "--account_id")
        .help("The resource ID of the buyers resource under which the creative is to be created. ")
        .required(true)
        .type(Integer.class);
    parser.addArgument("--advertiser_name")
        .help("The name of the company being advertised in the creative.")
        .setDefault("Test");
    parser.addArgument("-c", "--creative_id")
        .help("The user-specified creative ID. The maximum length of the creative ID is 128 bytes.")
        .setDefault(String.format("Video_Creative_%s", UUID.randomUUID()));
    parser.addArgument("--declared_attributes")
        .help("The creative attributes being declared. Specify each attribute separated by a " +
            "space.")
        .nargs("*")
        .setDefault(Collections.singletonList("CREATIVE_TYPE_VAST_VIDEO"));
    parser.addArgument("--declared_click_urls")
        .help("The click-through URLs being declared. Specify each URL separated by a space.")
        .nargs("*")
        .setDefault(Collections.singletonList("http://test.com"));
    parser.addArgument("--declared_restricted_categories")
        .help("The restricted categories being declared. Specify each category separated by a " +
            "space.")
        .nargs("*");
    parser.addArgument("--declared_vendor_ids")
        .help("The vendor IDs being declared. Specify each ID separated by a space.")
        .type(Integer.class)
        .nargs("*");
    parser.addArgument("--video_url")
        .help("The URL to fetch a video ad.")
        .setDefault("https://video.test.com/ads?id=123456&wprice=%%WINNING_PRICE%%");

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:\n%s", ex);
      System.exit(1);
    }

    execute(client, parsedArgs);
  }
}

PHP

<?php

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

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Buyers_Creatives;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;
use Google_Service_RealTimeBidding_Creative;
use Google_Service_RealTimeBidding_VideoContent;

/**
 * This example illustrates how to create video creatives for a given buyer account.
 */
class CreateVideoCreatives extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Account ID',
               'description' =>
                    'The resource ID of the buyers resource under which the creative is to be ' .
                    'created.',
                'required' => true
            ],
            [
                'name' => 'advertiser_name',
                'display' => 'Advertiser name',
                'description' => 'The name of the company being advertised in the creative.',
                'required' => false,
                'default' => 'Test'
            ],
            [
                'name' => 'creative_id',
                'display' => 'Creative ID',
                'description' =>
                    'The user-specified creative ID. The maximum length of the creative ID is ' .
                    '128 bytes',
                'required' => false,
                'default' => 'Video_Creative_' . uniqid()
            ],
            [
                'name' => 'declared_attributes',
                'display' => 'Declared attributes',
                'description' =>
                    'The creative attributes being declared. Specify each attribute separated ' .
                    'by a comma.',
                'required' => false,
                'is_array' => true,
                'default' => ['CREATIVE_TYPE_VAST_VIDEO']
            ],
            [
                'name' => 'declared_click_urls',
                'display' => 'Declared click URLs',
                'description' =>
                    'The click-through URLs being declared. Specify each URL separated by a comma.',
                'required' => false,
                'is_array' => true,
                'default' => ['http://test.com']
            ],
            [
                'name' => 'declared_restricted_categories',
                'display' => 'Declared restricted categories',
                'description' =>
                    'The restricted categories being declared. Specify each category separated ' .
                    'by a comma.',
                'required' => false,
                'is_array' => true
            ],
            [
                'name' => 'declared_vendor_ids',
                'display' => 'Declared vendor IDs',
                'description' =>
                    'The vendor IDs being declared. Specify each ID separated by a comma.',
                'required' => false,
                'is_array' => true
            ],
            [
                'name' => 'video_url',
                'display' => 'Video URL',
                'description' => 'The URL to fetch a video ad.',
                'required' => false,
                'default' => 'https://video.test.com/ads?id=123456&wprice=%%WINNING_PRICE%%'
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;
        $parentName = "buyers/$values[account_id]";

        $video = new Google_Service_RealTimeBidding_VideoContent();
        $video->videoUrl = $values['video_url'];

        $newCreative = new Google_Service_RealTimeBidding_Creative();
        $newCreative->advertiserName = $values['advertiser_name'];
        $newCreative->creativeId = $values['creative_id'];
        $newCreative->declaredAttributes = $values['declared_attributes'];
        $newCreative->declaredClickThroughUrls = $values['declared_click_urls'];
        $newCreative->declaredRestrictedCategories = $values['declared_restricted_categories'];
        $newCreative->declaredVendorIds = $values['declared_vendor_ids'];
        $newCreative->setVideo($video);

        print "<h2>Creating Creative for '$parentName':</h2>";
        $result = $this->service->buyers_creatives->create($parentName, $newCreative);
        $this->printResult($result);
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Create Buyer Video Creative';
    }
}

Python

#!/usr/bin/python
#
# Copyright 2020 Google Inc. All Rights Reserved.
#
# 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.

"""Creates a creative with video content for the given buyer account ID."""


import argparse
import datetime
import os
import pprint
import sys
import uuid

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError
import util


_BUYER_NAME_TEMPLATE = 'buyers/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'


def main(realtimebidding, args):
  account_id = args.account_id

  creative = {
    'advertiserName': args.advertiser_name,
    'creativeId': args.creative_id,
    'declaredAttributes': args.declared_attributes,
    'declaredClickThroughUrls': args.declared_click_urls,
    'declaredRestrictedCategories': args.declared_restricted_categories,
    'declaredVendorIds': [int(id) for id in args.declared_vendor_ids],
    'video': {
        'videoUrl': args.video_url
    }
  }

  print(f'Creating video creative for buyer account ID "{account_id}":')
  try:
    # Construct and execute the request.
    response = (realtimebidding.buyers().creatives().create(
        parent=_BUYER_NAME_TEMPLATE % account_id, body=creative).execute())
  except HttpError as e:
    print(e)
    sys.exit(1)

  pprint.pprint(response)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print(f'Unable to create realtimebidding service - {ex}')
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Creates a video creative for the given buyer account ID.')
  )

  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
      help=('The resource ID of the buyers resource under which the '
            'creative is to be created.'))
  # Optional fields.
  parser.add_argument(
      '--advertiser_name', default='Test',
      help='The name of the company being advertised in the creative.')
  parser.add_argument(
      '-c', '--creative_id', default='HTML_Creative_%s' % uuid.uuid4(),
      help=('The user-specified creative ID. The maximum length of the '
            'creative ID is 128 bytes.'))
  parser.add_argument(
      '--declared_attributes', nargs='*', default=['CREATIVE_TYPE_VAST_VIDEO'],
      help=('The creative attributes being declared. Specify each attribute '
            'separated by a space.'))
  parser.add_argument(
      '--declared_click_urls', nargs='*', default=['http://test.com'],
      help=('The click-through URLs being declared. Specify each URL '
            'separated by a space.'))
  parser.add_argument(
      '--declared_restricted_categories', nargs='*', default=[],
      help=('The restricted categories being declared. Specify each category '
            'separated by a space.'))
  parser.add_argument(
      '--declared_vendor_ids', nargs='*', default=[],
      help=('The vendor IDs being declared. Specify each ID separated by a '
            'space.'))
  parser.add_argument(
      '--video_url', help='The URL to fetch a video ad.',
      default='https://video.test.com/ads?id=123456&wprice=%%WINNING_PRICE%%')

  args = parser.parse_args()

  main(service, args)


Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2020 Google LLC
#
# License:: 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.
#
# Creates a creative with video content for the given buyer account ID.

require 'optparse'
require 'securerandom'

require_relative '../../../util'


def create_video_creatives(realtimebidding, options)
  parent = "buyers/#{options[:account_id]}"

  body = Google::Apis::RealtimebiddingV1::Creative.new(
      advertiser_name: options[:advertiser_name],
      creative_id: options[:creative_id],
      declared_attributes: options[:declared_attributes],
      declared_click_through_urls: options[:declared_click_urls],
      declared_resricted_categories: options[:declared_restricted_categories],
      declared_vendor_ids: options[:declared_vendor_ids],
      video: Google::Apis::RealtimebiddingV1::VideoContent.new(
          video_url: options[:video_url]
      )
  )

  puts "Creating video creative for buyer account '#{parent}'"

  creative = realtimebidding.create_buyer_creative(parent, creative_object=body)
  print_creative(creative)
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the buyers resource under which the creatives were created, This will be used to construct '\
      'the name used as a path parameter for the creatives.get request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'creative_id', 'The user-specified creative ID. The maximum length of the creative ID is 128 bytes.',
      short_alias: 'c', required: false, default_value: "Video_Creative_#{SecureRandom.uuid}"
    ),
    Option.new(
      'advertiser_name', 'The name of the company being advertised in the creative.', required: false,
      default_value: 'Test'
    ),
    Option.new(
      'declared_attributes', 'The creative attributes being declared. Specify each attribute separated by a comma.',
      required: false, type: Array, default_value: ['CREATIVE_TYPE_VAST_VIDEO']
    ),
    Option.new(
      'declared_click_urls', 'The click-through URLs being declared. Specify each URL separated by a comma.',
      required: false, type: Array, default_value: ['http://test.com']
    ),
    Option.new(
      'declared_restricted_categories',
      'The restricted categories being declared. Specify each category separated by a comma.',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'declared_vendor_ids', 'The vendor IDs being declared. Specify each ID separated by a space.',
      required: false, type: Array, default_value: []
    ),
    Option.new(
      'video_url', 'The URL to fetch a video ad.', required: false,
      default_value: 'https://video.test.com/ads?id=123456&wprice=%%WINNING_PRICE%%'
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    create_video_creatives(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

Retrieve an individual creative

The following demonstrates how once can retrieve an individual creative for a given buyer with buyers.creatives.get. Unless the view parameter is specified as FULL, the response will exclude most fields other than creativeServingDecision.

REST

Request

GET https://realtimebidding.googleapis.com/v1/buyers/<INSERT_ACCOUNT_ID_HERE>/creatives/HTML_Creative_09bb2ded-df72-42e6-a98f-28792b94ae4e?alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json

Response

{
  "accountId": "<ACCOUNT_ID>",
  "creativeId": "HTML_Creative_09bb2ded-df72-42e6-a98f-28792b94ae4e",
  "creativeFormat": "HTML",
  "creativeServingDecision": {
    "detectedProductCategories": [
      10016,
      10019,
      10141,
      10168,
      10754,
      10885,
      12206
    ],
    "detectedLanguages": [
      "en"
    ],
    "detectedAttributes": [
      "CREATIVE_TYPE_HTML"
    ],
    "lastStatusUpdate": "2020-07-30T04:47:31.616018Z",
    "dealsPolicyCompliance": {
      "status": "APPROVED"
    },
    "networkPolicyCompliance": {
      "status": "APPROVED"
    },
    "platformPolicyCompliance": {
      "status": "APPROVED"
    },
    "chinaPolicyCompliance": {
      "status": "APPROVED"
    },
    "russiaPolicyCompliance": {
      "status": "APPROVED"
    }
  }
}

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.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Buyers.Creatives
{
    /// <summary>
    /// Gets a single creative for the given buyer account ID and creative ID.
    /// </summary>
    public class GetCreatives : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public GetCreatives()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get { return "This code example gets a specific creative for a buyer account."; }
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            bool showHelp = false;

            string accountId = null;
            string creativeId = null;
            string view = null;

            OptionSet options = new OptionSet {
                "Get a creative for a given buyer account ID and creative ID.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the buyers resource under which the " +
                     "creatives were created. This will be used to construct the name used as " +
                     "a path parameter for the creatives.get request."),
                    a => accountId = a
                },
                {
                    "c|creative_id=",
                    ("[Required] The resource ID of the buyers.creatives resource for which the " +
                     "creative was created. This will be used to construct the name used as a " +
                     "path parameter for the creatives.get request."),
                    c => creativeId = c
                },
                {
                    "v|view=",
                    ("Controls the amount of information included in the response. By default, " +
                     "the creatives.get method only includes creativeServingDecision. This " +
                     "sample configures the view to return the full contents of the creative " +
                     "by setting this to \"FULL\"."),
                    v => view = v
                },
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Handle error conditions.
            if(extras.Count > 0)
            {
                Console.Error.WriteLine("Unknown arguments specified:");
                foreach(string arg in extras)
                {
                    Console.Error.WriteLine(arg);
                }
                Environment.Exit(1);
            }
            // Verify required arguments were set.
            if(accountId == null)
            {
                Console.Error.WriteLine("Required argument \"account_id\" not specified.");
                options.WriteOptionDescriptions(Console.Error);
                Environment.Exit(1);
            }
            else
            {
                parsedArgs["accountId"] = accountId;
            }

            if(creativeId == null)
            {
                Console.Error.WriteLine("Required argument \"creative_id\" not specified.");
                options.WriteOptionDescriptions(Console.Error);
                Environment.Exit(1);
            }
            else
            {
                parsedArgs["creative"] = creativeId;
            }
            // Set optional arguments.
            parsedArgs["view"] = view ?? "FULL";

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            string accountId = (string) parsedArgs["accountId"];
            string creativeId = (string) parsedArgs["creativeId"];
            string name = $"buyers/{accountId}/creatives/{creativeId}";

            BuyersResource.CreativesResource.GetRequest request =
                rtbService.Buyers.Creatives.Get(name);
            request.View = (BuyersResource.CreativesResource.GetRequest.ViewEnum) Enum.Parse(
                typeof(BuyersResource.CreativesResource.ListRequest.ViewEnum),
                (string) parsedArgs["view"],
                false);
            Creative response = null;

            Console.WriteLine("Getting creative with name: {0}", name);

            try
            {
                response = request.Execute();
            }
            catch (System.Exception exception)
            {
                Console.Error.WriteLine("Real-time Bidding API returned error response:\n{0}",
                                        exception.Message);
                Environment.Exit(1);
            }

            Utilities.PrintCreative(response);
        }
    }
}

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.api.services.samples.authorizedbuyers.realtimebidding.v1.buyers.creatives;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.Creative;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/**
 * This sample illustrates how to get a single creative for the given buyer account ID and creative
 * ID.
 */
public class GetCreatives {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) {
    Integer accountId = parsedArgs.getInt("account_id");
    String creativeId = parsedArgs.getString("creative_id");
    String name = String.format("buyers/%s/creatives/%s", accountId, creativeId);

    Creative creative = null;

    try {
      creative = client.buyers().creatives().get(name)
          .setView(parsedArgs.getString("view"))
          .execute();
    } catch(IOException ex) {
      System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
      System.exit(1);
    }

    System.out.printf("Found Creative with ID '%s' for buyer account ID '%d':\n", creativeId,
        accountId);
    Utils.printCreative(creative);
  }

  public static void main(String[] args) {
    ArgumentParser parser = ArgumentParsers.newFor("GetCreatives").build()
        .defaultHelp(true)
        .description(("Get a creative for the given buyer account ID and creative ID."));
    parser.addArgument("-a", "--account_id")
        .help("The resource ID of the buyers resource under which the creatives were created. " +
            "This will be used to construct the parent used as a path parameter for the " +
            "creatives.list request.")
        .required(true)
        .type(Integer.class);
    parser.addArgument("-c", "--creative_id")
        .help("The resource ID of the buyers.creatives resource for which the creative was " +
            "created. This will be used to construct the name used as a path parameter for the " +
            "creatives.get request.")
        .required(true);
    parser.addArgument("-v", "--view")
        .help("Controls the amount of information included in the response. By default, the " +
            "creatives.list method only includes creativeServingDecision. This sample configures " +
            "the view to return the full contents of the creatives by setting this to 'FULL'.")
        .choices("FULL", "SERVING_DECISION_ONLY")
        .setDefault("FULL");

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:\n%s", ex);
      System.exit(1);
    }

    execute(client, parsedArgs);
  }
}

PHP

<?php

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

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Buyers_Creatives;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;

/**
 * This example illustrates how to get a single creative for the given account and creative IDs.
 */
class GetCreatives extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Account ID',
                'required' => true,
                'description' =>
                    'The resource ID of the buyers resource under which the creative was ' .
                    'created. This will be used to construct the name used as a path parameter ' .
                    'for the creatives.get request.'
            ],
            [
                'name' => 'creative_id',
                'display' => 'Creative ID',
                'required' => true,
                'description' =>
                    'The resource ID of the buyers.creatives resource under which the creative ' .
                    'was created. This will be used to construct the name used as a path ' .
                    'parameter for the creatives.get request.'
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;

        $name = "buyers/$values[account_id]/creatives/$values[creative_id]";

        try {
            $creative = $this->service->buyers_creatives->get($name);
            print '<h2>Found creative.</h2>';
            $this->printResult($creative);
        } catch (Google_Service_Exception $ex) {
            if ($ex->getCode() === 404 || $ex->getCode() === 403) {
                print '<h1>Creative not found or can\'t access creative</h1>';
            } else {
                throw $ex;
            }
        }
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Get Creative';
    }
}

Python

#!/usr/bin/python
#
# Copyright 2020 Google Inc. All Rights Reserved.
#
# 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.

"""Gets a single creative for the given account and creative IDs."""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_CREATIVES_NAME_TEMPLATE = 'buyers/%s/creatives/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'
DEFAULT_CREATIVE_RESOURCE_ID = 'ENTER_CREATIVE_RESOURCE_ID_HERE'


def main(realtimebidding, account_id, creative_id):
  print(f'Get Creative with ID "{creative_id}" for account "{account_id}":')
  try:
    # Construct and execute the request.
    response = realtimebidding.buyers().creatives().get(
        name=_CREATIVES_NAME_TEMPLATE % (account_id, creative_id)).execute()
  except HttpError as e:
    print(e)
    sys.exit(1)

  pprint.pprint(response)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print(f'Unable to create realtimebidding service - {ex}')
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Get a creative for the given buyer account ID and '
                   'creative ID.'))
  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
      help=('The resource ID of the buyers resource under which the '
            'creative was created. This will be used to construct the '
            'name used as a path parameter for the creatives.get request.'))
  parser.add_argument(
      '-c', '--creative_id', default=DEFAULT_CREATIVE_RESOURCE_ID,
      help=('The resource ID of the buyers.creatives resource for which the '
            'creative was created. This will be used to construct the name '
            'used as a path parameter for the creatives.get request.'))

  args = parser.parse_args()

  main(service, args.account_id, args.creative_id)


Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2020 Google LLC
#
# License:: 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.
#
# Gets a single creative for the given account and creative IDs.

require 'optparse'

require_relative '../../../util'


def get_creatives(realtimebidding, options)
  name = "buyers/#{options[:account_id]}/creatives/#{options[:creative_id]}"

  puts "Get creative with name '#{name}'"

  creative = realtimebidding.get_buyer_creative(name, view: options[:view])
  print_creative(creative)
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the buyers resource under which the creatives were created, This will be used to construct '\
      'the name used as a path parameter for the creatives.get request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'creative_id',
      'The resource ID of the buyers.creatives resource for which the creative was created. This will be used to '\
      'construct the name used as a path parameter for the creatives.get request.',
      short_alias: 'c', required: true, default_value: nil
    ),
    Option.new(
      'view',
      'Controls the amount of information included in the response. By default, the creatives.get method only '\
      'includes creativeServingDecision. This sample configures the view to return the full contents of the creative'\
      'by setting this to FULL.',
      short_alias: 'v', required: false, default_value: 'FULL'
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    get_creatives(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

Retrieve a list of submitted creatives

The following demonstrates how one can retrieve a list of creatives for a given buyer with buyers.creatives.list. This method supports list filtering. Unless the view parameter is specified as FULL, the response will exclude most fields other than creativeServingDecision.

REST

Request

GET https://realtimebidding.googleapis.com/v1/buyers/<INSERT_ACCOUNT_ID_HERE>/creatives?filter=creativeServingDecision.networkPolicyCompliance.status%3DAPPROVED+AND+creativeFormat%3DHTML&view=FULL&pageSize=3&alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json

Response

{
  "creatives": [
    {
      "name": "buyers/<ACCOUNT_ID>/creatives/HTML_Creative_%2389d53648-1e9d-428e-bd60-06f8f81d8a0d",
      "accountId": "<ACCOUNT_ID>",
      "creativeId": "HTML_Creative_#89d53648-1e9d-428e-bd60-06f8f81d8a0d",
      "html": {
        "snippet": "<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 scrolling=no src=\\\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%\\\"></iframe>",
        "width": 300,
        "height": 250
      },
      "creativeFormat": "HTML",
      "declaredClickThroughUrls": [
        "http://test.com"
      ],
      "declaredAttributes": [
        "CREATIVE_TYPE_HTML"
      ],
      "advertiserName": "Test",
      "apiUpdateTime": "2020-07-17T23:34:48.072475Z",
      "activityMetrics": {
        "yesterday": {
          "spend": {
            "currencyCode": "USD"
          },
          "forgoneSpend": {
            "currencyCode": "USD"
          }
        },
        "last7Days": {
          "spend": {
            "currencyCode": "USD"
          },
          "forgoneSpend": {
            "currencyCode": "USD"
          }
        }
      },
      "previewUrl": "https://storage.googleapis.com/g-authorized-buyers-creative-previews/lVljTKfc2vIA0JiMoEawKsslu5cWrXgD_tuFwRADsyinpD5J2XYMX7eNAwQ",
      "creativeServingDecision": {
        "detectedProductCategories": [
          10016,
          10019,
          10141,
          10168,
          10754,
          10885,
          12206
        ],
        "detectedLanguages": [
          "en"
        ],
        "detectedAttributes": [
          "CREATIVE_TYPE_HTML"
        ],
        "lastStatusUpdate": "2020-07-18T08:24:46.847935Z",
        "dealsPolicyCompliance": {
          "status": "APPROVED"
        },
        "networkPolicyCompliance": {
          "status": "APPROVED"
        },
        "platformPolicyCompliance": {
          "status": "APPROVED"
        },
        "chinaPolicyCompliance": {
          "status": "DISAPPROVED"
        },
        "russiaPolicyCompliance": {
          "status": "DISAPPROVED"
        }
      }
    },
    {
      "name": "buyers/<ACCOUNT_ID>/creatives/HTML_Creative_%23ac0770fa-5294-4571-856e-9ec6f613e590",
      "accountId": "<ACCOUNT_ID>",
      "creativeId": "HTML_Creative_#ac0770fa-5294-4571-856e-9ec6f613e590",
      "html": {
        "snippet": "<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 scrolling=no src=\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%\"></iframe>",
        "width": 300,
        "height": 250
      },
      "creativeFormat": "HTML",
      "declaredClickThroughUrls": [
        "test.com"
      ],
      "declaredAttributes": [
        "CREATIVE_TYPE_HTML"
      ],
      "advertiserName": "Test",
      "apiUpdateTime": "2020-07-15T21:24:10.269378Z",
      "activityMetrics": {
        "yesterday": {
          "spend": {
            "currencyCode": "USD"
          },
          "forgoneSpend": {
            "currencyCode": "USD"
          }
        },
        "last7Days": {
          "spend": {
            "currencyCode": "USD"
          },
          "forgoneSpend": {
            "currencyCode": "USD"
          }
        }
      },
      "previewUrl": "https://storage.googleapis.com/g-authorized-buyers-creative-previews/hedyN-6bCXEA0JiMoD8I704lPjLIl_-GXo7AOqBnWQJaOnuH6w6hUWzre2A",
      "creativeServingDecision": {
        "detectedProductCategories": [
          10016,
          10019,
          10141,
          10168,
          10754,
          10885,
          12206
        ],
        "detectedLanguages": [
          "en"
        ],
        "detectedAttributes": [
          "CREATIVE_TYPE_HTML"
        ],
        "lastStatusUpdate": "2020-07-15T22:02:39.925606Z",
        "dealsPolicyCompliance": {
          "status": "APPROVED"
        },
        "networkPolicyCompliance": {
          "status": "APPROVED"
        },
        "platformPolicyCompliance": {
          "status": "APPROVED"
        },
        "chinaPolicyCompliance": {
          "status": "APPROVED"
        },
        "russiaPolicyCompliance": {
          "status": "APPROVED"
        }
      }
    },
    {
      "name": "buyers/<ACCOUNT_ID>/creatives/HTML_Creative_%2383fb53fa-e8be-42f8-88cd-30453f04ab9b",
      "accountId": "<ACCOUNT_ID>",
      "creativeId": "HTML_Creative_#83fb53fa-e8be-42f8-88cd-30453f04ab9b",
      "html": {
        "snippet": "<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 scrolling=no\n    src=\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%\">\n</iframe>\n",
        "width": 300,
        "height": 250
      },
      "creativeFormat": "HTML",
      "declaredClickThroughUrls": [
        "http://test.com"
      ],
      "declaredAttributes": [
        "CREATIVE_TYPE_HTML"
      ],
      "advertiserName": "Test",
      "version": 1,
      "apiUpdateTime": "2020-07-23T20:41:48.420172Z",
      "activityMetrics": {
        "yesterday": {
          "spend": {
            "currencyCode": "USD"
          },
          "forgoneSpend": {
            "currencyCode": "USD"
          }
        },
        "last7Days": {
          "spend": {
            "currencyCode": "USD"
          },
          "forgoneSpend": {
            "currencyCode": "USD"
          }
        }
      },
      "previewUrl": "https://storage.googleapis.com/g-authorized-buyers-creative-previews/vm8sg3ISJRsA0JiMoAT89KJdex1E9Bq9dPyRUSL9g9pu4P73NbwJOUM_G2U",
      "creativeServingDecision": {
        "detectedProductCategories": [
          10016,
          10019,
          10141,
          10168,
          10754,
          10885,
          12206
        ],
        "detectedLanguages": [
          "en"
        ],
        "detectedAttributes": [
          "CREATIVE_TYPE_HTML"
        ],
        "lastStatusUpdate": "2020-07-23T21:29:31.105040Z",
        "dealsPolicyCompliance": {
          "status": "APPROVED"
        },
        "networkPolicyCompliance": {
          "status": "APPROVED"
        },
        "platformPolicyCompliance": {
          "status": "APPROVED"
        },
        "chinaPolicyCompliance": {
          "status": "APPROVED"
        },
        "russiaPolicyCompliance": {
          "status": "APPROVED"
        }
      }
    }
  ],
  "nextPageToken": "CngKTPcAAAAA_____4AA__8AAP__AAD__wAA__8AAP__AAD__wAA__8AAP8B__5zbi01MzcyODQxMC03NTc4NzQ1OTI4MDI0NTAwODAxAAEQAyEEJCN6EliW_DkAAAAA_____0gDUABaCwnlcIbkBz11fxADYKWxoxIaWGNyZWF0aXZlU2VydmluZ0RlY2lzaW9uLm9wZW5BdWN0aW9uU2VydmluZ1N0YXR1cy5zdGF0dXM9QVBQUk9WRUQgQU5EIGNyZWF0aXZlRm9ybWF0PUhUTUwg166a-uyH6wI=",
  "totalSize": 25
}

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.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Buyers.Creatives
{
    /// <summary>
    /// Lists creatives for a given buyer account ID.
    /// </summary>
    public class ListCreatives : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public ListCreatives()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get { return "This code example lists all creatives for a given buyer account."; }
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            bool showHelp = false;
            string defaultFilter = "creativeServingDecision.networkPolicyCompliance.status=" +
                                   "APPROVED AND creativeFormat=HTML";
            string accountId = null;
            string filter = null;
            int? pageSize = null;
            string view = null;

            OptionSet options = new OptionSet {
                "List creatives for the given buyer account.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the buyers resource under which the " +
                     "creatives were created. This will be used to construct the parent used as " +
                     "a path parameter for the creatives.list request."),
                    a => accountId = a
                },
                {
                    "p|page_size=",
                    ("The number of rows to return per page. The server may return fewer rows " +
                     "than specified."),
                    (int p) => pageSize =  p
                },
                {
                    "f|filter=",
                    ("Query string to filter creatives. If no filter is specified, all active " +
                     "creatives will be returned. To demonstrate usage, the default behavior of" +
                     "this sample is to filter such that only approved HTML snippet creatives " +
                     "are returned."),
                    f => filter = f
                },
                {
                    "v|view=",
                    ("Controls the amount of information included in the response. By default, " +
                     "the creatives.list method only includes creativeServingDecision. This " +
                     "sample configures the view to return the full contents of the creatives " +
                     "by setting this to \"FULL\"."),
                    v => view = v
                },
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Handle error conditions.
            if(extras.Count > 0)
            {
                Console.Error.WriteLine("Unknown arguments specified:");
                foreach(string arg in extras)
                {
                    Console.Error.WriteLine(arg);
                }
                Environment.Exit(1);
            }
            // Verify required arguments were set.
            if(accountId == null)
            {
                Console.Error.WriteLine("Required argument \"account_id\" not specified.");
                options.WriteOptionDescriptions(Console.Error);
                Environment.Exit(1);
            }
            else
            {
                parsedArgs["accountId"] = accountId;
            }
            // Set optional arguments.
            parsedArgs["pageSize"] = pageSize ?? Utilities.MAX_PAGE_SIZE;
            parsedArgs["filter"] = filter ?? defaultFilter;
            parsedArgs["view"] = view ?? "FULL";

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            string accountId = (string) parsedArgs["accountId"];
            string parent = $"buyers/{accountId}";
            string pageToken = null;

            Console.WriteLine("Listing creatives for buyer account \"{0}\"", parent);
            do
            {
                BuyersResource.CreativesResource.ListRequest request =
                    rtbService.Buyers.Creatives.List(parent);
                request.Filter = (string) parsedArgs["filter"];
                request.PageSize = (int) parsedArgs["pageSize"];
                request.PageToken = pageToken;
                request.View = (BuyersResource.CreativesResource.ListRequest.ViewEnum) Enum.Parse(
                    typeof(BuyersResource.CreativesResource.ListRequest.ViewEnum),
                    (string) parsedArgs["view"],
                    false);

                ListCreativesResponse page = null;

                try
                {
                    page = request.Execute();
                }
                catch (System.Exception exception)
                {
                    Console.Error.WriteLine("Real-time Bidding API returned error response:\n{0}",
                                            exception.Message);
                    Environment.Exit(1);
                }

                var creatives = page.Creatives;
                pageToken = page.NextPageToken;

                if(creatives.Count == 0)
                {
                    Console.WriteLine("No creatives found for buyer account.");
                }
                else
                {
                    foreach (Creative creative in creatives)
                        {
                            Utilities.PrintCreative(creative);
                        }
                }
            }
            while(pageToken != null);
        }
    }
}

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.api.services.samples.authorizedbuyers.realtimebidding.v1.buyers.creatives;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.Creative;
import com.google.api.services.realtimebidding.v1.model.ListCreativesResponse;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/**
 * This sample illustrates how to list Creatives for a given buyer account ID.
 */
public class ListCreatives {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) {
    Integer accountId = parsedArgs.getInt("account_id");
    Integer pageSize = parsedArgs.getInt("page_size");
    String parentBuyerName = String.format("buyers/%s", accountId);
    String pageToken = null;

    System.out.printf("Found Creatives for buyer Account ID '%d':\n", accountId);

    do {
      List<Creative> creatives = null;

      try {
        ListCreativesResponse response = client.buyers().creatives().list(parentBuyerName)
            .setFilter(parsedArgs.getString("filter"))
            .setView(parsedArgs.getString("view"))
            .setPageSize(pageSize)
            .setPageToken(pageToken)
            .execute();

        creatives = response.getCreatives();
        pageToken = response.getNextPageToken();
      } catch(IOException ex) {
        System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
        System.exit(1);
      }
      if (creatives.isEmpty()) {
        System.out.println("No creatives found.");
      } else {
        for(Creative creative: creatives) {
          Utils.printCreative(creative);
        }
      }
    } while (pageToken != null);
  }

  public static void main(String[] args) {
    ArgumentParser parser = ArgumentParsers.newFor("ListCreatives").build()
        .defaultHelp(true)
        .description(("Lists creatives associated with the given buyer account."));
    parser.addArgument("-a", "--account_id")
        .help("The resource ID of the buyers resource under which the creatives were created. " +
            "This will be used to construct the parent used as a path parameter for the " +
            "creatives.list request.")
        .required(true)
        .type(Integer.class);
    parser.addArgument("-p", "--page_size")
        .help("The resource ID of the buyers resource under which the user lists were created. " +
            "This will be used to construct the parent used as a path parameter for the " +
            "userLists.list request.")
        .setDefault(Utils.getMaximumPageSize())
        .type(Integer.class);
    parser.addArgument("-f", "--filter")
        .help("Query string to filter creatives. If no filter is specified, all active creatives " +
            "will be returned. To demonstrate usage, the default behavior of this sample is to " +
            "filter such that only approved HTML snippet creatives are returned.")
        .setDefault("creativeServingDecision.networkPolicyCompliance.status=APPROVED " +
            "AND creativeFormat=HTML");
    parser.addArgument("-v", "--view")
        .help("Controls the amount of information included in the response. By default, the " +
            "creatives.list method only includes creativeServingDecision. This sample configures " +
            "the view to return the full contents of the creatives by setting this to 'FULL'.")
        .choices("FULL", "SERVING_DECISION_ONLY")
        .setDefault("FULL");

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:\n%s", ex);
      System.exit(1);
    }

    execute(client, parsedArgs);
  }
}

PHP

<?php

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

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Buyers_Creatives;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;

/**
 * This example illustrates how to list creatives for the given buyer's account ID.
 */
class ListCreatives extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Buyer account ID',
                'required' => true,
                'description' =>
                    'The resource ID of the buyers resource under which the creatives were ' .
                    'created. This will be used to construct the parent used as a path ' .
                    'parameter for the creatives.list request.'
            ],
            [
                'name' => 'filter',
                'display' => 'Filter',
                'required' => false,
                'description' =>
                    'Query string to filter creatives. If no filter is specified, all active ' .
                    'creatives will be returned. To demonstrate usage, the default behavior of ' .
                    'this sample is to filter such that only approved HTML snippet creatives ' .
                    'are returned.',
                'default' =>
                    'creativeServingDecision.networkPolicyCompliance.status=APPROVED ' .
                    'AND creativeFormat=HTML'
            ],
            [
                'name' => 'view',
                'display' => 'View',
                'required' => false,
                'description' =>
                    'Controls the amount of information included in the response. By default, ' .
                    'the creatives.list method only includes creativeServingDecision. This ' .
                    'sample configures the view to return the full contents of the creatives by ' .
                    'setting this to "FULL".',
                'default' => 'FULL'
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;

        $parentName = "buyers/$values[account_id]";

        $queryParams = [
            'filter' => $values['filter'],
            'pageSize' => 10,
            'view' => $values['view']
        ];

        $result = $this->service->buyers_creatives->listBuyersCreatives($parentName, $queryParams);

        print "<h2>Creatives found for '$parentName':</h2>";
        if (empty($result['creatives'])) {
            print '<p>No Creatives found</p>';
        } else {
            foreach ($result['creatives'] as $creative) {
                $this->printResult($creative);
            }
        }
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'List Buyer Creatives';
    }
}

Python

#!/usr/bin/python
#
# Copyright 2020 Google Inc. All Rights Reserved.
#
# 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.

"""Lists creatives for the given buyer account ID."""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_BUYER_NAME_TEMPLATE = 'buyers/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'


def main(realtimebidding, args):
  account_id = args.account_id
  list_filter = args.filter
  view = args.view
  page_size = args.page_size

  page_token = None
  more_pages = True

  print(f'Listing creatives for buyer account: "{account_id}".')
  while more_pages:
    try:
      # Construct and execute the request.
      response = realtimebidding.buyers().creatives().list(
          parent=_BUYER_NAME_TEMPLATE % account_id, pageToken=page_token,
          filter=list_filter, view=view, pageSize=page_size).execute()
    except HttpError as e:
      print(e)
      sys.exit(1)

    pprint.pprint(response)

    page_token = response.get('nextPageToken')
    more_pages = bool(page_token)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print(f'Unable to create realtimebidding service - {ex}')
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  default_list_filter = (
      'creativeServingDecision.networkPolicyCompliance.status=APPROVED '
      'AND creativeFormat=HTML')

  parser = argparse.ArgumentParser(
      description=('Lists creatives for the given buyer account.'))
  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
      help=('The resource ID of the buyers resource under which the '
            'creatives were created. This will be used to construct the '
            'parent used as a path parameter for the creatives.list request.'))
  parser.add_argument(
      '-p', '--page_size', default=util.MAX_PAGE_SIZE,
      help=('The number of rows to return per page. The server may return '
            'fewer rows than specified.'))
  # Optional fields.
  parser.add_argument(
      '-f', '--filter', default=default_list_filter,
      help=('Query string to filter creatives. If no filter is specified, all '
            'active creatives will be returned. To demonstrate usage, the '
            'default behavior of this sample is to filter such that only '
            'approved HTML snippet creatives are returned.'))
  parser.add_argument(
      '-v', '--view', default='FULL',
      help=('Controls the amount of information included in the response. By '
            'default, the creatives.list method only includes '
            'creativeServingDecision. This sample configures the view to '
            'return the full contents of the creatives by setting this to '
            '"FULL".'))

  args = parser.parse_args()

  main(service, args)


Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2020 Google LLC
#
# License:: 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.
#
# Retrieves creatives for a given buyer account ID.

require 'optparse'

require_relative '../../../util'


def list_creatives(realtimebidding, options)
  parent = "buyers/#{options[:account_id]}"
  filter = options[:filter]
  view = options[:view]
  page_size = options[:page_size]

  page_token = nil

  puts "Listing creatives for buyer account '#{parent}'"
  begin
    response = realtimebidding.list_buyer_creatives(
        parent, filter: filter, view: view, page_size: page_size,
        page_token: page_token
    )

    page_token = response.next_page_token

    unless response.creatives.nil?
      response.creatives.each do |creative|
        print_creative(creative)
      end
    else
      puts 'No creatives found for buyer account'
    end
  end until page_token == nil
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  default_list_filter = 'creativeServingDecision.networkPolicyCompliance.status=APPROVED AND creativeFormat=HTML'

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the buyers resource under which the creatives were created, This will be used to construct'\
      'the parent used as a path parameter for the creatives.list request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'filter',
      'Query string to filter creatives. If no filter is specified, all active creatives will be returned. To '\
      'demonstrate usage, the default behavior of this sample is to filter such that only approved HTML snippet '\
      'creatives are returned.',
      short_alias: 'f', required: false, default_value: default_list_filter
    ),
    Option.new(
      'view',
      'Controls the amount of information included in the response. By default, the creatives.list method only '\
      'includes creativeServingDecision. This sample configures the view to return the full contents of creatives by '\
      'setting this to FULL.',
      short_alias: 'v', required: false, default_value: 'FULL'
    ),
    Option.new(
      'page_size', 'The number of rows to return per page. The server may return fewer rows than specified.',
      type: Array, short_alias: 'u', required: false, default_value: MAX_PAGE_SIZE
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    list_creatives(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

Patch an existing creative

The following demonstrates how one can patch an existing creative for a given buyer with buyers.creatives.patch. A creative can only be patched if it has completed review, and will have its version incremented after a successful patch.

REST

Request

PATCH https://realtimebidding.googleapis.com/v1/buyers/<INSERT_ACCOUNT_ID_HERE>/creatives/HTML_Creative_09bb2ded-df72-42e6-a98f-28792b94ae4e?updateMask=advertiserName%2CdeclaredClickThroughUrls&alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json
 
{
  "advertiserName": "Test-Advertiser-ed901b94-8e6f-40ee-adc2-666fe2224e01",
  "declaredClickThroughUrls": [
    "https://test.clickurl.com/93d4666e-b5de-406b-9729-fa75b53e655c",
    "https://test.clickurl.com/db4939f0-79ba-4bfb-a21e-6e198a052de5",
    "https://test.clickurl.com/33e02bcb-ada2-4240-933e-afb356fbe8af"
  ]
}

Response

{
  "name": "buyers/<ACCOUNT_ID>/creatives/HTML_Creative_09bb2ded-df72-42e6-a98f-28792b94ae4e",
  "accountId": "<ACCOUNT_ID>",
  "creativeId": "HTML_Creative_09bb2ded-df72-42e6-a98f-28792b94ae4e",
  "html": {
    "snippet": "<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 scrolling=no src=\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%\"></iframe>",
    "width": 300,
    "height": 250
  },
  "creativeFormat": "HTML",
  "declaredClickThroughUrls": [
    "https://test.clickurl.com/93d4666e-b5de-406b-9729-fa75b53e655c",
    "https://test.clickurl.com/db4939f0-79ba-4bfb-a21e-6e198a052de5",
    "https://test.clickurl.com/33e02bcb-ada2-4240-933e-afb356fbe8af"
  ],
  "declaredAttributes": [
    "CREATIVE_TYPE_HTML"
  ],
  "advertiserName": "Test-Advertiser-ed901b94-8e6f-40ee-adc2-666fe2224e01",
  "version": 2,
  "apiUpdateTime": "2020-08-07T00:47:42.431231Z",
  "creativeServingDecision": {
    "lastStatusUpdate": "2020-08-07T00:47:42.432Z",
    "dealsPolicyCompliance": {
      "status": "PENDING_REVIEW"
    },
    "networkPolicyCompliance": {
      "status": "PENDING_REVIEW"
    },
    "platformPolicyCompliance": {
      "status": "PENDING_REVIEW"
    },
    "chinaPolicyCompliance": {
      "status": "PENDING_REVIEW"
    },
    "russiaPolicyCompliance": {
      "status": "PENDING_REVIEW"
    }
  }
}

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.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Buyers.Creatives
{
    /// <summary>
    /// Patches a creative with the specified name.
    /// </summary>
    public class PatchCreatives : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public PatchCreatives()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get { return "This code example patches a creative having the specified name."; }
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            bool showHelp = false;

            string accountId = null;
            string creativeId = null;

            OptionSet options = new OptionSet {
                "Patches the specified creative.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the buyers resource under which the " +
                     "creatives were created. This will be used to construct the name used as " +
                     "a path parameter for the creatives.get request."),
                    a => accountId = a
                },
                {
                    "c|creative_id=",
                    ("[Required] The resource ID of the buyers.creatives resource for which the " +
                     "creative was created. This will be used to construct the name used as a " +
                     "path parameter for the creatives.patch request."),
                    c => creativeId = c
                }
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Handle error conditions.
            if(extras.Count > 0)
            {
                Console.Error.WriteLine("Unknown arguments specified:");
                foreach(string arg in extras)
                {
                    Console.Error.WriteLine(arg);
                }
                Environment.Exit(1);
            }
            // Verify required arguments were set.
            if(accountId == null)
            {
                Console.Error.WriteLine("Required argument \"account_id\" not specified.");
                options.WriteOptionDescriptions(Console.Error);
                Environment.Exit(1);
            }
            else
            {
                parsedArgs["accountId"] = accountId;
            }

            if(creativeId == null)
            {
                Console.Error.WriteLine("Required argument \"creative_id\" not specified.");
                options.WriteOptionDescriptions(Console.Error);
                Environment.Exit(1);
            }
            else
            {
                parsedArgs["creativeId"] = creativeId;
            }

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            var accountId = (string) parsedArgs["accountId"];
            var creativeId = (string) parsedArgs["creativeId"];
            var name = $"buyers/{accountId}/creatives/{creativeId}";
            IList<String> declaredClickThroughUrls = new List<string>(new string[] {
                $"https://test.clickurl.com/{System.Guid.NewGuid()}",
                $"https://test.clickurl.com/{System.Guid.NewGuid()}",
                $"https://test.clickurl.com/{System.Guid.NewGuid()}"
            });

            Creative update = new Creative();
            update.AdvertiserName = $"Test-Advertiser-{System.Guid.NewGuid()}";
            update.DeclaredClickThroughUrls = declaredClickThroughUrls;

            BuyersResource.CreativesResource.PatchRequest request =
                rtbService.Buyers.Creatives.Patch(update, name);
            // Configure the update mask such that only the advertiserName and
            // declaredClickThroughUrls fields are updated. If not set, the patch method would
            // overwrite all other writable fields with a null value.
            request.UpdateMask = "advertiserName,declaredClickThroughUrls";

            Creative response = null;

            Console.WriteLine("Patching creative with name: {0}", name);

            try
            {
                response = request.Execute();
            }
            catch (System.Exception exception)
            {
                Console.Error.WriteLine("Real-time Bidding API returned error response:\n{0}",
                                        exception.Message);
                Environment.Exit(1);
            }

            Utilities.PrintCreative(response);
        }
    }
}

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.api.services.samples.authorizedbuyers.realtimebidding.v1.buyers.creatives;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.Creative;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/**
 * Patches a creative with the specified name.
 */
public class PatchCreatives {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) {
    Integer accountId = parsedArgs.getInt("account_id");
    String creativeId = parsedArgs.getString("creative_id");
    String name = String.format("buyers/%s/creatives/%s", accountId, creativeId);

    List<String> declaredClickThroughUrls = Arrays.asList(
        String.format("https://test.clickurl.com/%s", UUID.randomUUID()),
        String.format("https://test.clickurl.com/%s", UUID.randomUUID()),
        String.format("https://test.clickurl.com/%s", UUID.randomUUID())
        );

    Creative update = new Creative();
    update.setAdvertiserName(String.format("Test-Advertiser-%s", UUID.randomUUID()));
    update.setDeclaredClickThroughUrls(declaredClickThroughUrls);

    String uMask = "advertiserName,declaredClickThroughUrls";

    Creative creative = null;
    try {
      creative = client.buyers().creatives().patch(name, update).setUpdateMask(uMask).execute();
    } catch(IOException ex) {
    System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
    System.exit(1);
  }

    System.out.printf("Patched creative for buyer Account ID '%s':\n", accountId);
    Utils.printCreative(creative);
  }

  public static void main(String[] args) {
    ArgumentParser parser = ArgumentParsers.newFor("PatchCreatives").build()
        .defaultHelp(true)
        .description(("Patches the specified creative's advertiserName and " +
            "declaredClickThroughUrls."));
    parser.addArgument("-a", "--account_id")
        .help("The resource ID of the buyers resource under which the creative is to be created.")
        .required(true)
        .type(Integer.class);
    parser.addArgument("-c", "--creative_id")
        .help("The resource ID of the buyers.creatives resource for which the creative was " +
            "created. This will be used to construct the name used as a path parameter for the " +
            "creatives.patch request.")
        .required(true);

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:\n%s", ex);
      System.exit(1);
    }

    execute(client, parsedArgs);
  }
}

PHP

<?php

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

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Buyers_Creatives;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;
use Google_Service_RealTimeBidding_Creative;

/**
 * This example illustrates how to patch a creative with the specified account and creative IDs.
 */
class PatchCreatives extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Account ID',
                'description' =>
                    'The resource ID of the buyers resource under which the creative was ' .
                    'created. This will be used to construct the name used as a path parameter ' .
                    'for the creatives.patch request.',
                'required' => true
            ],
            [
                'name' => 'creative_id',
                'display' => 'Creative ID',
                'description' =>
                    'The resource ID of the buyers.creatives resource for which the creative ' .
                    'was created. This will be used to construct the name used as a path ' .
                    'parameter for the creatives.patch request.',
                'required' => true
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;

        $name = "buyers/$values[account_id]/creatives/$values[creative_id]";

        $patchedCreative = new Google_Service_RealTimeBidding_Creative();
        $patchedCreative->advertiserName = 'Test-Advertiser-' . uniqid();
        $patchedCreative->declaredClickThroughUrls = [
            'https://test.clickurl.com/' . uniqid(),
            'https://test.clickurl.com/' . uniqid(),
            'https://test.clickurl.com/' . uniqid()
        ];

        $queryParams = [
            'updateMask' => 'advertiserName,declaredClickThroughUrls'
        ];

        print "<h2>Patching Creative '$name':</h2>";
        $result = $this->service->buyers_creatives->patch($name, $patchedCreative, $queryParams);
        $this->printResult($result);
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Patch Buyer Creative';
    }
}

Python

#!/usr/bin/python
#
# Copyright 2020 Google Inc. All Rights Reserved.
#
# 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 patches a creative with the specified name."""


import argparse
import datetime
import os
import pprint
import sys
import uuid

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError
import util


_CREATIVES_NAME_TEMPLATE = 'buyers/%s/creatives/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'
DEFAULT_CREATIVE_RESOURCE_ID = 'ENTER_USERLIST_RESOURCE_ID_HERE'


def main(realtimebidding, args):
  account_id = args.account_id
  creative_id = args.creative_id

  creative = {
      'advertiserName': f'Test-Advertiser-{uuid.uuid4()}',
      'declaredClickThroughUrls': [f'https://test.clickurl.com/{uuid.uuid4()}'
                                   for _ in range(3)]
  }

  update_mask = ','.join(creative.keys())

  print(f'Patching creative with ID {creative_id} for buyer account ID '
        f'{account_id}:')
  try:
    # Construct and execute the request.
    response = (realtimebidding.buyers().creatives().patch(
                name=_CREATIVES_NAME_TEMPLATE % (account_id, creative_id),
                body=creative, updateMask=update_mask).execute())
  except HttpError as e:
    print(e)
    sys.exit(1)

  pprint.pprint(response)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print(f'Unable to create realtimebidding service - {ex}')
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Patches the specified creative.')
  )

  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
      help=('The resource ID of the buyers resource under which the '
            'userlist was created. This will be used to construct the '
            'name used as a path parameter for the userlists.patch request.'))
  parser.add_argument(
      '-c', '--creative_id', default=DEFAULT_CREATIVE_RESOURCE_ID,
      help='The resource ID of the buyers.creatives resource for which the '
            'creative was created. This will be used to construct the '
            'name used as a path parameter for the creatives.patch request.')

  args = parser.parse_args()

  main(service, args)


Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2020 Google LLC
#
# License:: 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 patches a creative with the specified name.

require 'optparse'
require 'securerandom'

require_relative '../../../util'


def patch_creatives(realtimebidding, options)
  name = "buyers/#{options[:account_id]}/creatives/#{options[:creative_id]}"

  declared_click_through_urls = [
      "https://test.clickurl.com/#{SecureRandom.uuid}",
      "https://test.clickurl.com/#{SecureRandom.uuid}",
      "https://test.clickurl.com/#{SecureRandom.uuid}"
  ]

  body = Google::Apis::RealtimebiddingV1::Creative.new(
      advertiser_name: options[:advertiser_name],
      declared_click_through_urls: declared_click_through_urls,
  )

  update_mask = 'advertiserName,declaredClickThroughUrls'

  puts "Patching creative with name '#{name}'"

  creative = realtimebidding.patch_buyer_creative(
      name, creative_object=body, update_mask: update_mask)
  print_creative(creative)
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the buyers resource under which the creative was created, This will be used to construct '\
      'the name used as a path parameter for the creatives.patch request.',
      type: Integer, short_alias: 'a', required: true,
      default_value: nil
    ),
    Option.new(
      'creative_id',
      'The resource ID of the buyers.creatives resource for which the creative was created. This will be used to '\
      'construct the name used as a path parameter for the creatives.patch request.',
      short_alias: 'c', required: true,
      default_value: nil
    ),
    Option.new(
      'advertiser_name', 'The name of the company being advertised in the creative.', required: false,
      default_value: "Advertiser ##{SecureRandom.uuid}"
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    patch_creatives(service, opts)
   rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

Using the Creatives resource as a bidder

Retrieve a list of submitted creatives

The following demonstrates how one can retrieve a list of creatives for a given bidder with bidders.creatives.list. This method supports list filtering. Unless the view parameter is specified as FULL, the response will exclude most fields other than creativeServingDecision.

REST

Request

GET https://realtimebidding.googleapis.com/v1/bidders/<INSERT_ACCOUNT_ID_HERE>/creatives?filter=creativeServingDecision.networkPolicyCompliance.status%3DAPPROVED+AND+creativeFormat%3DHTML&view=FULL&pageSize=3&alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json

Response

{
  "creatives": [
    {
      "name": "buyers/<ACCOUNT_ID1>/creatives/HTML_Creative_89d53648-1e9d-428e-bd60-06f8f81d8a0d",
      "accountId": "<ACCOUNT_ID1>",
      "creativeId": "HTML_Creative_89d53648-1e9d-428e-bd60-06f8f81d8a0d",
      "html": {
        "snippet": "<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 scrolling=no src=\\\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%\\\"></iframe>",
        "width": 300,
        "height": 250
      },
      "creativeFormat": "HTML",
      "declaredClickThroughUrls": [
        "http://test.com"
      ],
      "declaredAttributes": [
        "CREATIVE_TYPE_HTML"
      ],
      "advertiserName": "Test",
      "apiUpdateTime": "2020-07-17T23:34:48.072475Z",
      "activityMetrics": {
        "yesterday": {
          "spend": {
            "currencyCode": "USD"
          },
          "forgoneSpend": {
            "currencyCode": "USD"
          }
        },
        "last7Days": {
          "spend": {
            "currencyCode": "USD"
          },
          "forgoneSpend": {
            "currencyCode": "USD"
          }
        }
      },
      "previewUrl": "https://storage.googleapis.com/g-authorized-buyers-creative-previews/lVljTKfc2vIA0JiMoEawKsslu5cWrXgD_tuFwRADsyinpD5J2XYMX7eNAwQ",
      "creativeServingDecision": {
        "detectedProductCategories": [
          10016,
          10019,
          10141,
          10168,
          10754,
          10885,
          12206
        ],
        "detectedLanguages": [
          "en"
        ],
        "detectedAttributes": [
          "CREATIVE_TYPE_HTML"
        ],
        "lastStatusUpdate": "2020-07-18T08:24:46.847935Z",
        "dealsPolicyCompliance": {
          "status": "APPROVED"
        },
        "networkPolicyCompliance": {
          "status": "APPROVED"
        },
        "platformPolicyCompliance": {
          "status": "APPROVED"
        },
        "chinaPolicyCompliance": {
          "status": "DISAPPROVED"
        },
        "russiaPolicyCompliance": {
          "status": "DISAPPROVED"
        }
      }
    },
    {
      "name": "buyers/<ACCOUNT_ID2>/creatives/HTML_Creative_ac0770fa-5294-4571-856e-9ec6f613e590",
      "accountId": "<ACCOUNT_ID2>",
      "creativeId": "HTML_Creative_ac0770fa-5294-4571-856e-9ec6f613e590",
      "html": {
        "snippet": "<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 scrolling=no src=\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%\"></iframe>",
        "width": 300,
        "height": 250
      },
      "creativeFormat": "HTML",
      "declaredClickThroughUrls": [
        "test.com"
      ],
      "declaredAttributes": [
        "CREATIVE_TYPE_HTML"
      ],
      "advertiserName": "Test",
      "apiUpdateTime": "2020-07-15T21:24:10.269378Z",
      "activityMetrics": {
        "yesterday": {
          "spend": {
            "currencyCode": "USD"
          },
          "forgoneSpend": {
            "currencyCode": "USD"
          }
        },
        "last7Days": {
          "spend": {
            "currencyCode": "USD"
          },
          "forgoneSpend": {
            "currencyCode": "USD"
          }
        }
      },
      "previewUrl": "https://storage.googleapis.com/g-authorized-buyers-creative-previews/hedyN-6bCXEA0JiMoD8I704lPjLIl_-GXo7AOqBnWQJaOnuH6w6hUWzre2A",
      "creativeServingDecision": {
        "detectedProductCategories": [
          10016,
          10019,
          10141,
          10168,
          10754,
          10885,
          12206
        ],
        "detectedLanguages": [
          "en"
        ],
        "detectedAttributes": [
          "CREATIVE_TYPE_HTML"
        ],
        "lastStatusUpdate": "2020-07-15T22:02:39.925606Z",
        "dealsPolicyCompliance": {
          "status": "APPROVED"
        },
        "networkPolicyCompliance": {
          "status": "APPROVED"
        },
        "platformPolicyCompliance": {
          "status": "APPROVED"
        },
        "chinaPolicyCompliance": {
          "status": "APPROVED"
        },
        "russiaPolicyCompliance": {
          "status": "APPROVED"
        }
      }
    },
    {
      "name": "buyers/<ACCOUNT_ID3>/creatives/HTML_Creative_83fb53fa-e8be-42f8-88cd-30453f04ab9b",
      "accountId": "<ACCOUNT_ID3>",
      "creativeId": "HTML_Creative_83fb53fa-e8be-42f8-88cd-30453f04ab9b",
      "html": {
        "snippet": "<iframe marginwidth=0 marginheight=0 height=600 frameborder=0 width=160 scrolling=no\n    src=\"https://test.com/ads?id=123456&curl=%%CLICK_URL_ESC%%&wprice=%%WINNING_PRICE_ESC%%\">\n</iframe>\n",
        "width": 300,
        "height": 250
      },
      "creativeFormat": "HTML",
      "declaredClickThroughUrls": [
        "http://test.com"
      ],
      "declaredAttributes": [
        "CREATIVE_TYPE_HTML"
      ],
      "advertiserName": "Test",
      "version": 1,
      "apiUpdateTime": "2020-07-23T20:41:48.420172Z",
      "activityMetrics": {
        "yesterday": {
          "spend": {
            "currencyCode": "USD"
          },
          "forgoneSpend": {
            "currencyCode": "USD"
          }
        },
        "last7Days": {
          "spend": {
            "currencyCode": "USD"
          },
          "forgoneSpend": {
            "currencyCode": "USD"
          }
        }
      },
      "previewUrl": "https://storage.googleapis.com/g-authorized-buyers-creative-previews/vm8sg3ISJRsA0JiMoAT89KJdex1E9Bq9dPyRUSL9g9pu4P73NbwJOUM_G2U",
      "creativeServingDecision": {
        "detectedProductCategories": [
          10016,
          10019,
          10141,
          10168,
          10754,
          10885,
          12206
        ],
        "detectedLanguages": [
          "en"
        ],
        "detectedAttributes": [
          "CREATIVE_TYPE_HTML"
        ],
        "lastStatusUpdate": "2020-07-23T21:29:31.105040Z",
        "dealsPolicyCompliance": {
          "status": "APPROVED"
        },
        "networkPolicyCompliance": {
          "status": "APPROVED"
        },
        "platformPolicyCompliance": {
          "status": "APPROVED"
        },
        "chinaPolicyCompliance": {
          "status": "APPROVED"
        },
        "russiaPolicyCompliance": {
          "status": "APPROVED"
        }
      }
    }
  ],
  "nextPageToken": "CnkKTPcAAAAA_____4AA__8AAP__AAD__wAA__8AAP__AAD__wAA__8AAP8B__5zbi01MzcyODQxMC03NTc4NzQ1OTI4MDI0NTAwODAxAAEQAyEEJCN6EliW_DkAAAAA_____0gDUABaCwntdJgOpe997BADYNmu5KoFGlhjcmVhdGl2ZVNlcnZpbmdEZWNpc2lvbi5vcGVuQXVjdGlvblNlcnZpbmdTdGF0dXMuc3RhdHVzPUFQUFJPVkVEIEFORCBjcmVhdGl2ZUZvcm1hdD1IVE1MII6l_Yzxh-sC",
  "totalSize": 25
}

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.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Bidders.Creatives
{
    /// <summary>
    /// Lists creatives for a given bidder account ID.
    /// </summary>
    public class ListCreatives : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public ListCreatives()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get { return "This code example lists all creatives for a given bidder account."; }
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            bool showHelp = false;
            string defaultFilter = "creativeServingDecision.networkPolicyCompliance.status=" +
                                   "APPROVED AND creativeFormat=HTML";
            string accountId = null;
            string filter = null;
            int? pageSize = null;
            string view = null;

            OptionSet options = new OptionSet {
                "List creatives for the given buyer account.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the bidders resource under which the " +
                     "creatives were created. This will be used to construct the parent used as " +
                     "a path parameter for the creatives.list request."),
                    a => accountId = a
                },
                {
                    "p|page_size=",
                    ("The number of rows to return per page. The server may return fewer rows " +
                     "than specified."),
                    (int p) => pageSize =  p
                },
                {
                    "f|filter=",
                    ("Query string to filter creatives. If no filter is specified, all active " +
                     "creatives will be returned. To demonstrate usage, the default behavior of" +
                     "this sample is to filter such that only approved HTML snippet creatives " +
                     "are returned."),
                    f => filter = f
                },
                {
                    "v|view=",
                    ("Controls the amount of information included in the response. By default, " +
                     "the creatives.list method only includes creativeServingDecision. This " +
                     "sample configures the view to return the full contents of the creatives " +
                     "by setting this to \"FULL\"."),
                    v => view = v
                },
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Handle error conditions.
            if(extras.Count > 0)
            {
                Console.Error.WriteLine("Unknown arguments specified:");
                foreach(string arg in extras)
                {
                    Console.Error.WriteLine(arg);
                }
                Environment.Exit(1);
            }
            // Verify required arguments were set.
            if(accountId == null)
            {
                Console.Error.WriteLine("Required argument \"account_id\" not specified.");
                options.WriteOptionDescriptions(Console.Error);
                Environment.Exit(1);
            }
            else
            {
                parsedArgs["accountId"] = accountId;
            }
            // Set optional arguments.
            parsedArgs["pageSize"] = pageSize ?? Utilities.MAX_PAGE_SIZE;
            parsedArgs["filter"] = filter ?? defaultFilter;
            parsedArgs["view"] = view ?? "FULL";

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            string accountId = (string) parsedArgs["accountId"];
            string parent = $"bidders/{accountId}";
            string pageToken = null;

            Console.WriteLine("Listing creatives for bidder account \"{0}\"", parent);
            do
            {
                BiddersResource.CreativesResource.ListRequest request =
                   rtbService.Bidders.Creatives.List(parent);
                request.Filter = (string) parsedArgs["filter"];
                request.PageSize = (int) parsedArgs["pageSize"];
                request.PageToken = pageToken;
                request.View = (BiddersResource.CreativesResource.ListRequest.ViewEnum) Enum.Parse(
                    typeof(BiddersResource.CreativesResource.ListRequest.ViewEnum),
                    (string) parsedArgs["view"],
                    false);

                ListCreativesResponse page = null;

                try
                {
                    page = request.Execute();
                }
                catch (System.Exception exception)
                {
                    Console.Error.WriteLine("Real-time Bidding API returned error response:\n{0}",
                                            exception.Message);
                    Environment.Exit(1);
                }

                var creatives = page.Creatives;
                pageToken = page.NextPageToken;

                if(creatives.Count == 0)
                {
                    Console.WriteLine("No creatives found for buyer account.");
                }
                else
                {
                    foreach (Creative creative in creatives)
                        {
                            Utilities.PrintCreative(creative);
                        }
                }
            }
            while(pageToken != null);
        }
    }
}

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.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.Creative;
import com.google.api.services.realtimebidding.v1.model.ListCreativesResponse;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/**
 * This sample illustrates how to list Creatives for a given bidder account ID.
 *
 * Note that unless filtered, this will include creatives from all buyer accounts under the bidder.
 */
public class ListCreatives {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) {
    Integer accountId = parsedArgs.getInt("account_id");
    Integer pageSize = parsedArgs.getInt("page_size");
    String parentBuyerName = String.format("bidders/%s", accountId);
    String pageToken = null;

    System.out.printf("Found Creatives for bidder Account ID '%d':\n", accountId);

    do {
      List<Creative> creatives = null;

      try {
        ListCreativesResponse response = client.bidders().creatives().list(parentBuyerName)
            .setFilter(parsedArgs.getString("filter"))
            .setView(parsedArgs.getString("view"))
            .setPageSize(pageSize)
            .setPageToken(pageToken)
            .execute();

        creatives = response.getCreatives();
        pageToken = response.getNextPageToken();
      } catch(IOException ex) {
        System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
        System.exit(1);
      }
      if (creatives.isEmpty()) {
        System.out.println("No creatives found.");
      } else {
        for(Creative creative: creatives) {
          Utils.printCreative(creative);
        }
      }
    } while (pageToken != null);
  }

  public static void main(String[] args) {
    ArgumentParser parser = ArgumentParsers.newFor("ListCreatives").build()
        .defaultHelp(true)
        .description(("Lists creatives for the given bidder account."));
    parser.addArgument("-a", "--account_id")
        .help("The resource ID of the bidders resource under which the creatives were created by " +
            "buyers. This will be used to construct the parent used as a path parameter for the " +
            "creatives.list request.")
        .required(true)
        .type(Integer.class);
    parser.addArgument("-p", "--page_size")
        .help("The resource ID of the buyers resource under which the user lists were created. " +
            "This will be used to construct the parent used as a path parameter for the " +
            "userLists.list request.")
        .setDefault(Utils.getMaximumPageSize())
        .type(Integer.class);
    parser.addArgument("-f", "--filter")
        .help("Query string to filter creatives. If no filter is specified, all active creatives " +
            "will be returned. To demonstrate usage, the default behavior of this sample is to " +
            "filter such that only approved HTML snippet creatives are returned.")
        .setDefault("creativeServingDecision.networkPolicyCompliance.status=APPROVED " +
            "AND creativeFormat=HTML");
    parser.addArgument("-v", "--view")
        .help("Controls the amount of information included in the response. By default, the " +
            "creatives.list method only includes creativeServingDecision. This sample configures " +
            "the view to return the full contents of the creatives by setting this to 'FULL'.")
        .choices("FULL", "SERVING_DECISION_ONLY")
        .setDefault("FULL");

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:\n%s", ex);
      System.exit(1);
    }

    execute(client, parsedArgs);
  }
}

PHP

<?php

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

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Bidders_Creatives;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;

/**
 * This example illustrates how to list creatives for the given bidder's account ID.
 *
 * Note that unless filtered, this will include creatives from all buyer accounts under the
 * bidder.
 */
class ListCreatives extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Bidder account ID',
                'required' => true,
                'description' =>
                    'The resource ID of the bidders resource under which the creatives were ' .
                    'created. This will be used to construct the parent used as a path ' .
                    'parameter for the creatives.list request.'
            ],
            [
                'name' => 'filter',
                'display' => 'Filter',
                'required' => false,
                'description' =>
                    'Query string to filter creatives. If no filter is specified, all active ' .
                    'creatives will be returned. To demonstrate usage, the default behavior of ' .
                    'this sample is to filter such that only approved HTML snippet creatives ' .
                    'are returned.',
                'default' =>
                    'creativeServingDecision.networkPolicyCompliance.status=APPROVED ' .
                    'AND creativeFormat=HTML'
            ],
            [
                'name' => 'view',
                'display' => 'View',
                'required' => false,
                'description' =>
                    'Controls the amount of information included in the response. By default, ' .
                    'the creatives.list method only includes creativeServingDecision. This ' .
                    'sample configures the view to return the full contents of the creatives by ' .
                    'setting this to "FULL".',
                'default' => 'FULL'
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;

        $parentName = "bidders/$values[account_id]";

        $queryParams = [
            'filter' => $values['filter'],
            'pageSize' => 10,
            'view' => $values['view']
        ];

        $result = $this->service->bidders_creatives->listBiddersCreatives($parentName, $queryParams);

        print "<h2>Creatives found for '$parentName':</h2>";
        if (empty($result['creatives'])) {
            print '<p>No Creatives found</p>';
        } else {
            foreach ($result['creatives'] as $creative) {
                $this->printResult($creative);
            }
        }
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'List Bidder Creatives';
    }
}

Python

#!/usr/bin/python
#
# Copyright 2020 Google Inc. All Rights Reserved.
#
# 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.

"""Lists creatives for the given bidder's account ID.

Note that unless filtered, this will include creatives from all buyer accounts
under the bidder.
"""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_BIDDER_NAME_TEMPLATE = 'bidders/%s'

DEFAULT_BIDDER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE'


def main(realtimebidding, args):
  account_id = args.account_id
  list_filter = args.filter
  view = args.view
  page_size = args.page_size

  page_token = None
  more_pages = True

  print(f'Listing creatives for bidder account: "{account_id}".')
  while more_pages:
    try:
      # Construct and execute the request.
      response = realtimebidding.bidders().creatives().list(
          parent=_BIDDER_NAME_TEMPLATE % account_id, pageToken=page_token,
          filter=list_filter, view=view, pageSize=page_size).execute()
    except HttpError as e:
      print(e)
      sys.exit(1)

    pprint.pprint(response)

    page_token = response.get('nextPageToken')
    more_pages = bool(page_token)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print(f'Unable to create realtimebidding service - {ex}')
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  default_list_filter = (
      'creativeServingDecision.networkPolicyCompliance.status=APPROVED '
      'AND creativeFormat=HTML')

  parser = argparse.ArgumentParser(
      description=('Lists creatives for the given bidder account.'))
  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BIDDER_RESOURCE_ID,
      help=('The resource ID of the bidders resource under which the '
            'creatives were created by a buyer. This will be used to '
            'construct the parent used as a path parameter for the '
            'creatives.list request.'))
  parser.add_argument(
      '-p', '--page_size', default=util.MAX_PAGE_SIZE,
      help=('The number of rows to return per page. The server may return '
            'fewer rows than specified.'))
  # Optional fields.
  parser.add_argument(
      '-f', '--filter', default=default_list_filter,
      help=('Query string to filter creatives. If no filter is specified, all '
            'active creatives will be returned. To demonstrate usage, the '
            'default behavior of this sample is to filter such that only '
            'approved HTML snippet creatives are returned.'))
  parser.add_argument(
      '-v', '--view', default='FULL',
      help=('Controls the amount of information included in the response. By '
            'default, the creatives.list method only includes '
            'creativeServingDecision. This sample configures the view to '
            'return the full contents of the creatives by setting this to '
            '"FULL".'))

  args = parser.parse_args()

  main(service, args)


Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2020 Google LLC
#
# License:: 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.
#
# Lists creatives for the given bidder's account ID.
#
# Note that unless filtered, this will include creatives from all buyer
# accounts under the bidder.

require 'optparse'

require_relative '../../../util'


def list_creatives(realtimebidding, options)
  parent = "bidders/#{options[:account_id]}"
  filter = options[:filter]
  view = options[:view]
  page_size = options[:page_size]

  page_token = nil

  puts "Listing creatives for bidder account '#{parent}'"
  begin
    response = realtimebidding.list_bidder_creatives(
        parent, filter: filter, view: view, page_size: page_size, page_token: page_token
    )

    page_token = response.next_page_token

    unless response.creatives.nil?
      response.creatives.each do |creative|
        print_creative(creative)
      end
    else
      puts 'No creatives found for buyer account'
    end
  end until page_token == nil
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  default_list_filter = 'creativeServingDecision.networkPolicyCompliance'\
                        '.status=APPROVED AND creativeFormat=HTML'

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the bidders resource under which the creatives were created, This will be used to '\
      'construct the parent used as a path parameter for the creatives.list request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
    Option.new(
      'filter',
      'Query string to filter creatives. If no filter is specified, all active creatives will be returned. To '\
      'demonstrate usage, the default behavior of this sample is to filter such that only approved HTML snippet '\
      'creatives are returned.',
      short_alias: 'f', required: false, default_value: default_list_filter
    ),
    Option.new(
      'view',
      'Controls the amount of information included in the response. By default, the creatives.list method only '\
      'includes creativeServingDecision. This sample configures the view to return the full contents of creatives by '\
      'setting this to FULL.',
      short_alias: 'v', required: false, default_value: 'FULL'
    ),
    Option.new(
      'page_size', 'The number of rows to return per page. The server may return fewer rows than specified.',
      type: Array, short_alias: 'u', required: false, default_value: MAX_PAGE_SIZE
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    list_creatives(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

Watch creative status changes with Google Cloud Pub/Sub

The following demonstrates how one can configure their bidder account to watch for creative status changes with bidders.creatives.watch. When configured, Authorized Buyers will create a Google Cloud Pub/Sub subscription for the bidder, and send messages to it for each change in creative status for buyers under the bidder account.

REST

Request

POST https://realtimebidding.googleapis.com/v1/bidders/<INSERT_ACCOUNT_ID_HERE>/creatives:watch?alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json

Response

{
  "topic": "projects/realtimebidding-pubsub/topics/topic<ACCOUNT_ID>",
  "subscription": "projects/realtimebidding-pubsub/subscriptions/subscription<ACCOUNT_ID>"
}

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.Apis.RealTimeBidding.v1;
using Google.Apis.RealTimeBidding.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.RealTimeBidding.Examples.v1.Bidders.Creatives
{
    /// <summary>
    /// Enables monitoring of changes in creative statuses for a given bidder.
    ///
    /// Watched creatives will have changes to their status posted to Google Cloud Pub/Sub. For
    /// more details on Google Cloud Pub/Sub, see: https://cloud.google.com/pubsub/docs
    ///
    /// For an example of pulling creative status changes from a Google Cloud Pub/Sub subscription,
    /// see PullWatchedCreativesSubscription.cs.
    /// </summary>
    public class WatchCreatives : ExampleBase
    {
        private RealTimeBiddingService rtbService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public WatchCreatives()
        {
            rtbService = Utilities.GetRealTimeBiddingService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get
            {
                return "Enables watching creative status changes for the given bidder account.";
            }
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            bool showHelp = false;

            string accountId = null;

            OptionSet options = new OptionSet {
                "Patches the specified creative.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the buyers resource under which the " +
                     "creatives were created. This will be used to construct the name used as " +
                     "a path parameter for the creatives.get request."),
                    a => accountId = a
                }
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Handle error conditions.
            if(extras.Count > 0)
            {
                Console.Error.WriteLine("Unknown arguments specified:");
                foreach(string arg in extras)
                {
                    Console.Error.WriteLine(arg);
                }
                Environment.Exit(1);
            }
            // Verify required arguments were set.
            if(accountId == null)
            {
                Console.Error.WriteLine("Required argument \"account_id\" not specified.");
                options.WriteOptionDescriptions(Console.Error);
                Environment.Exit(1);
            }
            else
            {
                parsedArgs["accountId"] = accountId;
            }

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            var accountId = (string) parsedArgs["accountId"];
            var parentBidderName = $"bidders/{accountId}";

            WatchCreativesRequest body = new WatchCreativesRequest();

            BiddersResource.CreativesResource.WatchRequest request =
                rtbService.Bidders.Creatives.Watch(body, parentBidderName);

            WatchCreativesResponse response = null;

            Console.WriteLine("Watching creative status changes for bidder account with name: {0}",
                              parentBidderName);

            try
            {
                response = request.Execute();
            }
            catch (System.Exception exception)
            {
                Console.Error.WriteLine("Real-time Bidding API returned error response:\n{0}",
                                        exception.Message);
                Environment.Exit(1);
            }

            Console.WriteLine("- Topic: {0}", response.Topic);
            Console.WriteLine("- Subscription: {0}", response.Subscription);
        }
    }
}

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.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders;

import com.google.api.services.realtimebidding.v1.RealTimeBidding;
import com.google.api.services.realtimebidding.v1.model.WatchCreativesRequest;
import com.google.api.services.realtimebidding.v1.model.WatchCreativesResponse;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/**
 * Enables monitoring of changes of a creative status for a given bidder.
 *
 * Watched creatives will have changes to their status posted to Google Cloud Pub/Sub. For more
 * details on Google Cloud Pub/Sub, see: https://cloud.google.com/pubsub/docs
 *
 * For an example of pulling creative status changes from a Google Cloud Pub/Sub subscription, see
 * PullWatchedCreativesSubscription.java.
 */
public class WatchCreatives {

  public static void execute(RealTimeBidding client, Namespace parsedArgs) {
    Integer accountId = parsedArgs.getInt("account_id");
    String parentBidderName = String.format("bidders/%s", accountId);

    WatchCreativesResponse response = null;
    try {
      response = client.bidders().creatives().watch(parentBidderName, new WatchCreativesRequest())
          .execute();
    } catch(IOException ex) {
      System.out.printf("RealTimeBidding API returned error response:\n%s", ex);
      System.exit(1);
    }

    System.out.printf("Watching creative status changes for bidder account '%s'.':\n",
        accountId);
    System.out.printf("- Topic: %s\n", response.getTopic());
    System.out.printf("- Subscription: %s\n", response.getSubscription());
  }

  public static void main(String[] args) {
    ArgumentParser parser = ArgumentParsers.newFor("WatchCreatives").build()
        .defaultHelp(true)
        .description(("Enables watching creative status changes for the given bidder account."));
    parser.addArgument("-a", "--account_id")
        .help("The resource ID of a bidder account. This will be used to construct the parent " +
            "used as a path parameter for the creatives.watch request.")
        .required(true)
        .type(Integer.class);

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    RealTimeBidding client = null;
    try {
      client = Utils.getRealTimeBiddingClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create RealTimeBidding API service:\n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:\n%s", ex);
      System.exit(1);
    }

    execute(client, parsedArgs);
  }
}

PHP

<?php

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

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Bidders_Creatives;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;
use Google_Service_RealTimeBidding_WatchCreativesRequest;

/**
 * Enables monitoring of changes in status of a given bidder's creatives.
 *
 * Watched creatives will have changes to their status posted to Google Cloud Pub/Sub. For more
 * details on Google Cloud Pub/Sub, see:
 * https://cloud.google.com/pubsub/docs
 *
 * For an example of pulling creative status changes from a Google Cloud Pub/Sub subscription, see
 * PullWatchedCreativesSubscription.php.
 */
class WatchCreatives extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServiceRealTimeBidding($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'account_id',
                'display' => 'Bidder account ID',
                'required' => true,
                'description' =>
                    'The resource ID of a bidder account. This will be used to construct the ' .
                    'parent used as a path parameter for the creatives.watch request.'
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;

        $parentName = "bidders/$values[account_id]";

        $watch_request = new Google_Service_RealTimeBidding_WatchCreativesRequest();

        try {
            $response = $this->service->bidders_creatives->watch($parentName, $watch_request);
            print "<h2>Watching creative status for bidder '$parentName'.</h2>";
            $this->printResult($response);
        } catch (Google_Service_Exception $ex) {
            if ($ex->getCode() === 404 || $ex->getCode() === 403) {
                print '<h1>Bidder not found or can\'t access account.</h1>';
            } else {
                throw $ex;
            }
        }
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Watch Bidder Creatives';
    }
}

Python

#!/usr/bin/python
#
# Copyright 2020 Google Inc. All Rights Reserved.
#
# 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.

"""Enables monitoring of changes of a creative status for a given bidder.

Watched creatives will have changes to their status posted to Google Cloud
Pub/Sub. For more details on Google Cloud Pub/Sub, see:
https://cloud.google.com/pubsub/docs

For an example of pulling creative status changes from a Google Cloud Pub/Sub
subscription, see pull_watched_creatives_subscription.py.
"""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_BIDDER_NAME_TEMPLATE = 'bidders/%s'

DEFAULT_BIDDER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE'


def main(realtimebidding, args):
  account_id = args.account_id

  print(f'Watching creative status changes for bidder account "{account_id}":')

  try:
    # Construct and execute the request.
    response = realtimebidding.bidders().creatives().watch(
        parent=_BIDDER_NAME_TEMPLATE % account_id).execute()
  except HttpError as e:
    print(e)
    sys.exit(1)

  pprint.pprint(response)


if __name__ == '__main__':
  try:
    service = util.GetService(version='v1')
  except IOError as ex:
    print(f'Unable to create realtimebidding service - {ex}')
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Enables watching creative status changes for the given '
                   'bidder account.'))
  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BIDDER_RESOURCE_ID,
      help=('The resource ID of a bidder account. This will be used to '
            'construct the parent used as a path parameter for the '
            'creatives.watch request.'))

  args = parser.parse_args()

  main(service, args)


Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2020 Google LLC
#
# License:: 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.
#
# Enables monitoring of changes of a creative status for a given bidder.
#
# Watched creatives will have changes to their status posted to Google Cloud Pub/Sub. For more details on Google Cloud
# Pub/Sub, see: https://cloud.google.com/pubsub/docs
#
# For an example of pulling creative status changes from the Google Cloud Pub/Sub subscription, see
# pull_watched_creatives_subscription.rb.

require 'optparse'

require_relative '../../../util'


def watch_creatives(realtimebidding, options)
  parent = "bidders/#{options[:account_id]}"

  puts "Watching creative status changes for bidder account '#{parent}':"

  response = realtimebidding.watch_creatives(parent)

  puts "\tTopic: #{response.topic}"
  puts "\tSubscription: #{response.subscription}"
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise 'Unable to create service, was the KEY_FILE in util.rb set? Error message: #{e.message}'
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'account_id',
      'The resource ID of the bidder account. This will be used to construct the parent used as a path parameter for '\
      'the creatives.watch request.',
      type: Integer, short_alias: 'a', required: true, default_value: nil
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    watch_creatives(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end

Using Google Cloud Pub/Sub to view creative status changes

The following demonstrates how one can pull and acknowledge messages for a bidder's creative status changes using the Google Cloud Pub/Sub API's projects.subscriptions.pull and projects.subscriptions.acknowledge methods.

Each message received will include the creativeFormat, creativeId, and accountId attributes in order to identify the creative. The data field includes the base64-encoded JSON representation of the creative's creativeServingDecision. You can use the ackId to acknowledge that the message was received with the subscriptions.acknowledge API call.

REST

Pull Request

POST https://pubsub.googleapis.com/v1/projects/realtimebidding-pubsub/subscriptions/subscription<INSERT_ACCOUNT_ID_HERE>:pull?alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json
 
{
  "maxMessages": 5
}

Pull Response

{
  "receivedMessages": [
    {
      "ackId": "TgQhIT4wPkVTRFAGFixdRkhRNxkIaFEOT14jPzUgKEUSAAgUBXx9ckRLdV4zdQdRDRlzemInYwxAVFNCW3RfURsfWVx-VQZVDRh6eGR2a1IWCABGVnp3qPT2zoHmIB1tNfaZ_6hASoL904h0Zhs9XxJLLD5-Jz1FQV5AEkwsCERJUytDCypYEQ",
      "message": {
        "data": "eyJkZXRlY3RlZENsaWNrVGhyb3VnaFVybHMiOlsiaHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS8iLCJodHRwczovL3d3dy5nb29nbGUuY29tLyNzcGZcdTAwM2QxNTk0ODUwNjEyNzEwIl0sImRldGVjdGVkUHJvZHVjdENhdGVnb3JpZXMiOlsxMDAwMywxMDAwNywxMDAxMCwxMDAxMywxMDAxNiwxMDAxOSwxMDA0MiwxMDA4MiwxMDEwMywxMDE0MSwxMDE2OCwxMDc1NCwxMDg4NSwxMjIwNiwxMzQxOF0sImRldGVjdGVkTGFuZ3VhZ2VzIjpbImVuIl0sImRldGVjdGVkRG9tYWlucyI6WyJnb29nbGUuY29tIl0sImRldGVjdGVkQXR0cmlidXRlcyI6WyJDUkVBVElWRV9UWVBFX0hUTUwiXSwibGFzdFN0YXR1c1VwZGF0ZSI6IjIwMjAtMDctMTVUMjI6MjY6MzQuNzk2WiIsImRlYWxzUG9saWN5Q29tcGxpYW5jZSI6eyJzdGF0dXMiOiJBUFBST1ZFRCJ9LCJuZXR3b3JrUG9saWN5Q29tcGxpYW5jZSI6eyJzdGF0dXMiOiJBUFBST1ZFRCJ9LCJwbGF0Zm9ybVBvbGljeUNvbXBsaWFuY2UiOnsic3RhdHVzIjoiQVBQUk9WRUQifSwiY2hpbmFQb2xpY3lDb21wbGlhbmNlIjp7InN0YXR1cyI6IkFQUFJPVkVEIn0sInJ1c3NpYVBvbGljeUNvbXBsaWFuY2UiOnsic3RhdHVzIjoiQVBQUk9WRUQifX0=",
        "attributes": {
          "creativeFormat": "ADX_FORMAT_NATIVE",
          "creativeId": "Native_Creative_7eb070ce-7268-4dd2-9640-15e28fd16892",
          "accountId": "<ACCOUNT_ID1>"
        },
        "messageId": "1401855318592354",
        "publishTime": "2020-08-04T15:00:27.410Z"
      }
    },
    {
      "ackId": "TgQhIT4wPkVTRFAGFixdRkhRNxkIaFEOT14jPzUgKEUSAAgUBXx9ckRLdV4zdQdRDRlzemInYwxAVFNCW3RfURofWVx-VQZVDRh6dGFxYlMWAgpFW393qPT2zoHmIB1tNfaZ_6hASoL904h0Zhs9XxJLLD5-Jz1FQV5AEkwsCERJUytDCypYEQ",
      "message": {
        "data": "eyJkZXRlY3RlZENsaWNrVGhyb3VnaFVybHMiOlsiaHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS8iXSwiZGV0ZWN0ZWRQcm9kdWN0Q2F0ZWdvcmllcyI6WzEwMDAzLDEwMDA3LDEwMDEwLDEwMDEzLDEwMDE2LDEwMDE5LDEwMDQyLDEwMDgyLDEwMTAzLDEwMTQxLDEwMTY4LDEwNzU0LDEwODg1LDEyMjA2LDEzNDE4XSwiZGV0ZWN0ZWRMYW5ndWFnZXMiOlsiZW4iXSwiZGV0ZWN0ZWREb21haW5zIjpbImdvb2dsZS5jb20iXSwiZGV0ZWN0ZWRBdHRyaWJ1dGVzIjpbIk5BVElWRV9FTElHSUJJTElUWV9FTElHSUJMRSJdLCJsYXN0U3RhdHVzVXBkYXRlIjoiMjAyMC0wNy0xOFQxMTozNDozMy41MTVaIiwiZGVhbHNQb2xpY3lDb21wbGlhbmNlIjp7InN0YXR1cyI6IkFQUFJPVkVEIn0sIm5ldHdvcmtQb2xpY3lDb21wbGlhbmNlIjp7InN0YXR1cyI6IkFQUFJPVkVEIn0sInBsYXRmb3JtUG9saWN5Q29tcGxpYW5jZSI6eyJzdGF0dXMiOiJBUFBST1ZFRCJ9LCJjaGluYVBvbGljeUNvbXBsaWFuY2UiOnsic3RhdHVzIjoiQVBQUk9WRUQifSwicnVzc2lhUG9saWN5Q29tcGxpYW5jZSI6eyJzdGF0dXMiOiJBUFBST1ZFRCJ9fQ==",
        "attributes": {
          "creativeFormat": "ADX_FORMAT_NATIVE",
          "creativeId": "Native_Creative_10fdd7a1-8f3d-4026-a12b-3fb823dff23e",
          "accountId": "<ACCOUNT_ID2>"
        },
        "messageId": "1401890489538081",
        "publishTime": "2020-08-04T15:00:27.410Z"
      }
    },
    {
      "ackId": "ISE-MD5FU0RQBhYsXUZIUTcZCGhRDk9eIz81IChFEgAIFAV8fXBCU3VfXndoUQ0Zcn1gcmkIFghRRFF3XVEZB2hObXUlcQwdcn9ncm5bGwUFRFR_WVgz_oen-qi9BBclSpKK96NvM9nsl9lPZiU9XxJLLD5-Jz1FQV5AEkwsCERJUytDCypYEU4E",
      "message": {
        "data": "eyJkZXRlY3RlZFByb2R1Y3RDYXRlZ29yaWVzIjpbMTAwMTYsMTAwMTksMTAxNDEsMTAxNjgsMTA3NTQsMTA4ODUsMTIyMDZdLCJkZXRlY3RlZExhbmd1YWdlcyI6WyJlbiJdLCJkZXRlY3RlZEF0dHJpYnV0ZXMiOlsiQ1JFQVRJVkVfVFlQRV9WQVNUX1ZJREVPIl0sImxhc3RTdGF0dXNVcGRhdGUiOiIyMDIwLTA3LTMwVDIyOjU3OjI0LjgxMFoiLCJkZWFsc1BvbGljeUNvbXBsaWFuY2UiOnsic3RhdHVzIjoiQVBQUk9WRUQifSwibmV0d29ya1BvbGljeUNvbXBsaWFuY2UiOnsic3RhdHVzIjoiRElTQVBQUk9WRUQiLCJ0b3BpY3MiOlt7InBvbGljeVRvcGljIjoiVklERU9fQURTX09USEVSIiwiaGVscENlbnRlclVybCI6Imh0dHBzOi8vc3VwcG9ydC5nb29nbGUuY29tL2Fkc3BvbGljeS9hbnN3ZXIvMjY3OTk0MCIsImV2aWRlbmNlcyI6W3sidmFzdCI6eyJwYXJzaW5nRXJyb3JzIjpbIklOVkFMSURfWE1MX1NZTlRBWCJdfX1dfV19LCJwbGF0Zm9ybVBvbGljeUNvbXBsaWFuY2UiOnsic3RhdHVzIjoiQVBQUk9WRUQifSwiY2hpbmFQb2xpY3lDb21wbGlhbmNlIjp7InN0YXR1cyI6IkRJU0FQUFJPVkVEIn0sInJ1c3NpYVBvbGljeUNvbXBsaWFuY2UiOnsic3RhdHVzIjoiRElTQVBQUk9WRUQifX0=",
        "attributes": {
          "creativeId": "Video_Creative_1193239f-a5dd-40c2-8472-34913a3f202c",
          "creativeFormat": "ADX_FORMAT_VIDEO_VAST",
          "accountId": "<ACCOUNT_ID3>"
        },
        "messageId": "1402674184717163",
        "publishTime": "2020-08-04T20:18:11.890Z"
      }
    },
    {
      "ackId": "ISE-MD5FU0RQBhYsXUZIUTcZCGhRDk9eIz81IChFEgAIFAV8fXBCU3VfXndoUQ0Zcn1gcmkIFghRRFF3XVEZB2lObXUlcQwdcn9nfG5eGwYKTVp_WVMz_oen-qi9BBclSpKK96NvM9nsl9lPZiU9XxJLLD5-Jz1FQV5AEkwsCERJUytDCypYEU4E",
      "message": {
        "data": "eyJkZXRlY3RlZEF0dHJpYnV0ZXMiOlsiQ1JFQVRJVkVfVFlQRV9IVE1MIl0sImxhc3RTdGF0dXNVcGRhdGUiOiIyMDIwLTA3LTMwVDIzOjM0OjQzLjAxOVoiLCJkZWFsc1BvbGljeUNvbXBsaWFuY2UiOnsic3RhdHVzIjoiQVBQUk9WRUQifSwibmV0d29ya1BvbGljeUNvbXBsaWFuY2UiOnsic3RhdHVzIjoiRElTQVBQUk9WRUQiLCJ0b3BpY3MiOlt7InBvbGljeVRvcGljIjoiREVTVElOQVRJT05fTk9UX0NSQVdMQUJMRSIsImhlbHBDZW50ZXJVcmwiOiJodHRwczovL3N1cHBvcnQuZ29vZ2xlLmNvbS9hZHNwb2xpY3kvYW5zd2VyLzYzNjg2NjEiLCJldmlkZW5jZXMiOlt7ImRlc3RpbmF0aW9uTm90Q3Jhd2xhYmxlIjp7ImNyYXdsZWRVcmwiOiJodHRwczovL3Rlc3QuY2xpY2t1cmwuY29tLzA0YWUxM2Y0LTM2OGEtNDYwNS05NGNhLWM2OWVmNzE4MDVjOSIsInJlYXNvbiI6IlVOUkVBQ0hBQkxFX1JPQk9UUyIsImNyYXdsVGltZSI6IjIwMjAtMDgtMDRUMDA6MTU6MjFaIn19LHsiZGVzdGluYXRpb25Ob3RDcmF3bGFibGUiOnsiY3Jhd2xlZFVybCI6Imh0dHBzOi8vdGVzdC5jbGlja3VybC5jb20vOGU2NDQwOTYtYWEwOC00OTEzLTkyMDgtZTJlYThkOTkxZDEzIiwicmVhc29uIjoiVU5SRUFDSEFCTEVfUk9CT1RTIiwiY3Jhd2xUaW1lIjoiMjAyMC0wOC0wM1QyMzo0ODo0MloifX0seyJkZXN0aW5hdGlvbk5vdENyYXdsYWJsZSI6eyJjcmF3bGVkVXJsIjoiaHR0cHM6Ly90ZXN0LmNsaWNrdXJsLmNvbS9mYmVmMDdjNC02ZGM1LTRlMmYtYjM5Yi1mYjc4OGE3YTFlNGMiLCJyZWFzb24iOiJVTlJFQUNIQUJMRV9ST0JPVFMiLCJjcmF3bFRpbWUiOiIyMDIwLTA4LTA0VDAwOjE1OjIwWiJ9fV19XX0sInBsYXRmb3JtUG9saWN5Q29tcGxpYW5jZSI6eyJzdGF0dXMiOiJBUFBST1ZFRCJ9LCJjaGluYVBvbGljeUNvbXBsaWFuY2UiOnsic3RhdHVzIjoiQVBQUk9WRUQifSwicnVzc2lhUG9saWN5Q29tcGxpYW5jZSI6eyJzdGF0dXMiOiJBUFBST1ZFRCJ9fQ==",
        "attributes": {
          "creativeId": "HTML_Creative_5e230148-2a6a-4ac7-b8a6-024ca06e3305",
          "accountId": "<ACCOUNT_ID2>",
          "creativeFormat": "ADX_FORMAT_HTML_SNIPPET"
        },
        "messageId": "1402694487889168",
        "publishTime": "2020-08-04T20:18:11.890Z"
      }
    },
    {
      "ackId": "ISE-MD5FU0RQBhYsXUZIUTcZCGhRDk9eIz81IChFEgAIFAV8fXBCU3VdXHdoUQ0Zcn1gcmkLRgMHQwErW1EaB2hObXUlcQwdcn9nfW5dFAcKQ1J3X1Iz_oen-qi9BBclSpKK96NvM9nsl9lPZiU9XxJLLD5-Jz1FQV5AEkwsCERJUytDCypYEU4E",
      "message": {
        "data": "eyJkZXRlY3RlZFByb2R1Y3RDYXRlZ29yaWVzIjpbMTAwMTYsMTAwMTksMTAxNDEsMTAxNjgsMTA3NTQsMTA4ODUsMTIyMDZdLCJkZXRlY3RlZExhbmd1YWdlcyI6WyJlbiJdLCJkZXRlY3RlZEF0dHJpYnV0ZXMiOlsiQ1JFQVRJVkVfVFlQRV9IVE1MIl0sImxhc3RTdGF0dXNVcGRhdGUiOiIyMDIwLTA3LTIyVDIzOjUyOjE4Ljk0N1oiLCJkZWFsc1BvbGljeUNvbXBsaWFuY2UiOnsic3RhdHVzIjoiQVBQUk9WRUQifSwibmV0d29ya1BvbGljeUNvbXBsaWFuY2UiOnsic3RhdHVzIjoiQVBQUk9WRUQifSwicGxhdGZvcm1Qb2xpY3lDb21wbGlhbmNlIjp7InN0YXR1cyI6IkFQUFJPVkVEIn0sImNoaW5hUG9saWN5Q29tcGxpYW5jZSI6eyJzdGF0dXMiOiJBUFBST1ZFRCJ9LCJydXNzaWFQb2xpY3lDb21wbGlhbmNlIjp7InN0YXR1cyI6IkFQUFJPVkVEIn19",
        "attributes": {
          "creativeFormat": "ADX_FORMAT_HTML_SNIPPET",
          "creativeId": "HTML_Creative_3e250341-3b6f-daf8-c3b4-131bd09e4217",
          "accountId": "<ACCOUNT_ID1>"
        },
        "messageId": "1402684776861909",
        "publishTime": "2020-08-04T20:18:12.095Z"
      }
    }
  ]
}

Acknowledge Request

POST https://pubsub.googleapis.com/v1/projects/realtimebidding-pubsub/subscriptions/subscription<INSERT_ACCOUNT_ID_HERE>:acknowledge?alt=json
Authorization: Bearer <INSERT_ACCESS_TOKEN_HERE>
Content-Type: application/json
 
{
  "ackIds": [
    "TgQhIT4wPkVTRFAGFixdRkhRNxkIaFEOT14jPzUgKEUSAAgUBXx9ckRLdV4zdQdRDRlzemInYwxAVFNCW3RfURsfWVx-VQZVDRh6eGR2a1IWCABGVnp3qPT2zoHmIB1tNfaZ_6hASoL904h0Zhs9XxJLLD5-Jz1FQV5AEkwsCERJUytDCypYEQ",
    "TgQhIT4wPkVTRFAGFixdRkhRNxkIaFEOT14jPzUgKEUSAAgUBXx9ckRLdV4zdQdRDRlzemInYwxAVFNCW3RfURofWVx-VQZVDRh6dGFxYlMWAgpFW393qPT2zoHmIB1tNfaZ_6hASoL904h0Zhs9XxJLLD5-Jz1FQV5AEkwsCERJUytDCypYEQ",
    "ISE-MD5FU0RQBhYsXUZIUTcZCGhRDk9eIz81IChFEgAIFAV8fXBCU3VfXndoUQ0Zcn1gcmkIFghRRFF3XVEZB2hObXUlcQwdcn9ncm5bGwUFRFR_WVgz_oen-qi9BBclSpKK96NvM9nsl9lPZiU9XxJLLD5-Jz1FQV5AEkwsCERJUytDCypYEU4E",
    "ISE-MD5FU0RQBhYsXUZIUTcZCGhRDk9eIz81IChFEgAIFAV8fXBCU3VfXndoUQ0Zcn1gcmkIFghRRFF3XVEZB2lObXUlcQwdcn9nfG5eGwYKTVp_WVMz_oen-qi9BBclSpKK96NvM9nsl9lPZiU9XxJLLD5-Jz1FQV5AEkwsCERJUytDCypYEU4E",
    "ISE-MD5FU0RQBhYsXUZIUTcZCGhRDk9eIz81IChFEgAIFAV8fXBCU3VdXHdoUQ0Zcn1gcmkLRgMHQwErW1EaB2hObXUlcQwdcn9nfW5dFAcKQ1J3X1Iz_oen-qi9BBclSpKK96NvM9nsl9lPZiU9XxJLLD5-Jz1FQV5AEkwsCERJUytDCypYEU4E"
  ]
}

Acknowledge Response

{}

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.Apis.Pubsub.v1;
using Google.Apis.Pubsub.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.Json;

namespace Google.Apis.RealTimeBidding.Examples.v1.Bidders.Creatives
{
    /// <summary>
    /// Pulls creative status changes from a Google Cloud Pub/Sub subscription.
    ///
    /// Note that messages do not expire until they are acknowledged; set the acknowledgement
    /// argument to "true" to acknowledge receiving all messages sent in the response.
    ///
    /// To learn more about Google Cloud Pub/Sub, read the developer documentation:
    /// https://cloud.google.com/pubsub/docs/overview
    /// https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions/list
    /// https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions/acknowledge
    /// </summary>
    public class PullWatchedCreativesSubscription : ExampleBase
    {
        private PubsubService pubSubService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public PullWatchedCreativesSubscription()
        {
            pubSubService = Utilities.GetPubSubService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get { return ("This code example pulls creative status changes (if any) from a " +
                          "specified Google Cloud Pub/Sub subscription."); }
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            bool showHelp = false;

            string subscriptionName = null;
            int? maxMessages  = null;
            bool? acknowledge = null;

            OptionSet options = new OptionSet {
                ("Pulls creative status changes (if any) from a specified Google Cloud Pub/Sub " +
                 "subscription."),
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "s|subscription_name=",
                    ("[Required] The Google Cloud Pub/Sub subscription to be pulled. This value " +
                     "would be returned in the response from the bidders.creatives.watch " +
                     "method, and should be provided as-is in the form: " +
                     "\"projects/realtimebidding-pubsub/subscriptions/{subscription_id}\""),
                    s => subscriptionName = s
                },
                {
                    "m|max_messages=",
                    "The maximum number of messages to be returned in a single pull.",
                    (int m) => maxMessages =  m
                },
                {
                    "a|acknowledge",
                    ("Specify this argument to indicate that you want to acknowledge messages " +
                     "pulled from the subscription. Acknowledged messages won't appear in the " +
                     "subsequent responses to pulls from the subscription. By default, messages " +
                     "will not be acknowledged."),
                    a => acknowledge = a != null
                }
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

            // Show help message.
            if(showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Handle error conditions.
            if(extras.Count > 0)
            {
                Console.Error.WriteLine("Unknown arguments specified:");
                foreach(string arg in extras)
                {
                    Console.Error.WriteLine(arg);
                }
                Environment.Exit(1);
            }
            // Verify required arguments were set.
            if(subscriptionName == null)
            {
                Console.Error.WriteLine("Required argument \"subscription_name\" not specified.");
                options.WriteOptionDescriptions(Console.Error);
                Environment.Exit(1);
            }
            else
            {
                parsedArgs["subscription_name"] = subscriptionName;
            }
            // Set optional arguments.
            parsedArgs["max_messages"] = maxMessages ?? Utilities.MAX_PAGE_SIZE;
            parsedArgs["acknowledge"] = acknowledge ?? false;

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            string subscriptionName = (string) parsedArgs["subscription_name"];

            Console.WriteLine("Retrieving messages from subscription: \"{0}\"", subscriptionName);

            PullRequest pullRequest = new PullRequest();
            pullRequest.MaxMessages = (int?) parsedArgs["max_messages"];

            PullResponse response = null;

            try
            {
                response = pubSubService.Projects.Subscriptions.Pull(
                    pullRequest, subscriptionName).Execute();
            }
            catch (System.Exception exception)
            {
                Console.Error.WriteLine("Google Cloud Pub/Sub API returned error response:\n{0}",
                                        exception.Message);
                Environment.Exit(1);
            }

            var ackIds = new List<string>();
            IList<ReceivedMessage> receivedMessages = response.ReceivedMessages;

            if(receivedMessages.Count == 0)
            {
                Console.Out.WriteLine("No messages received from the subscription.");
            }
            else
            {
                var options = new JsonSerializerOptions();
                options.WriteIndented = true;

                foreach(ReceivedMessage receivedMessage in receivedMessages)
                {
                ackIds.Add(receivedMessage.AckId);
                PubsubMessage message = receivedMessage.Message;
                IDictionary<string, string> messageAttributes = message.Attributes;
                var accountId = messageAttributes["accountId"];
                var creativeId = messageAttributes["creativeId"];

                Console.Out.WriteLine("* Creative found for buyer account ID \"{0}\" with " +
                                      "creative ID \"{1}\" has been updated with the following " +
                                      "creative status:\n", accountId, creativeId);

                byte[] data = Convert.FromBase64String(message.Data);
                var decodedString = Encoding.UTF8.GetString(data);
                JsonElement jsonData = JsonSerializer.Deserialize<JsonElement>(decodedString);

                Console.Out.WriteLine(JsonSerializer.Serialize(jsonData, options));
                }

                if((bool) parsedArgs["acknowledge"])
                {
                    AcknowledgeRequest acknowledgeRequest = new AcknowledgeRequest();
                    acknowledgeRequest.AckIds = ackIds;

                    Console.Out.WriteLine(
                        "Acknowledging all {0} messages pulled from the subscription.",
                        ackIds.Count);

                    try
                    {
                        pubSubService.Projects.Subscriptions.Acknowledge(acknowledgeRequest,
                                                                         subscriptionName);
                    }
                    catch (System.Exception exception)
                    {
                        Console.Error.WriteLine(
                            "Google Cloud Pub/Sub API returned error response:\n{0}",
                            exception.Message);
                        Environment.Exit(1);
                    }
                }
            }

        }
    }
}

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.api.services.samples.authorizedbuyers.realtimebidding.v1.bidders;

import static net.sourceforge.argparse4j.impl.Arguments.storeTrue;

import com.google.api.services.pubsub.Pubsub;
import com.google.api.services.pubsub.model.AcknowledgeRequest;
import com.google.api.services.pubsub.model.PubsubMessage;
import com.google.api.services.pubsub.model.PullRequest;
import com.google.api.services.pubsub.model.PullResponse;
import com.google.api.services.pubsub.model.ReceivedMessage;
import com.google.api.services.samples.authorizedbuyers.realtimebidding.Utils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/**
 * Pulls creative status updates from a Google Cloud Pub/Sub subscription.
 *
 * Note that messages do not expire until they are acknowledged; set the acknowledged argument to
 * True to acknowledge receiving all messages sent in the response.
 *
 * To learn more about Google Cloud Pub/Sub, read the developer documentation:
 * https://cloud.google.com/pubsub/docs/overview
 * https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions/list
 * https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions/acknowledge
 */
public class PullWatchedCreativesSubscription {

  public static void execute(Pubsub client, Namespace parsedArgs) {
    String subscriptionName = parsedArgs.getString("subscription_name");

    System.out.printf("Retrieving messages from subscription: '%s'\n", subscriptionName);

    PullRequest pullRequest = new PullRequest();
    pullRequest.setMaxMessages(parsedArgs.getInt("max_messages"));

    PullResponse response = null;

    try {
      response = client.projects().subscriptions().pull(subscriptionName, pullRequest).execute();

    } catch(IOException ex) {
      System.out.printf("Pubsub API returned error response while pulling subscription:\n%s\n",
          ex);
      System.exit(1);
    }

    List<String> ackIds = new ArrayList<>();
    List<ReceivedMessage> receivedMessages = response.getReceivedMessages();
    if (receivedMessages.isEmpty()) {
      System.out.println("No messages received from the subscription.");
    } else {
      Gson gson = new GsonBuilder().setPrettyPrinting().create();

      for (ReceivedMessage receivedMessage : receivedMessages) {
        ackIds.add(receivedMessage.getAckId());
        PubsubMessage message = receivedMessage.getMessage();
        Map<String, String> messageAttributes = message.getAttributes();
        String accountId = messageAttributes.get("accountId");
        String creativeId = messageAttributes.get("creativeId");

        System.out.printf("* Creative found for buyer account ID '%s' with creative ID '%s' " +
            "has been updated with the following creative status:\n", accountId, creativeId);

        String decodedData = new String(message.decodeData());
        JsonElement jsonElement = JsonParser.parseString(decodedData);
        System.out.printf("%s\n\n", gson.toJson(jsonElement));
      }

      if (parsedArgs.getBoolean("acknowledge")) {
        AcknowledgeRequest acknowledgeRequest = new AcknowledgeRequest();
        acknowledgeRequest.setAckIds(ackIds);

        System.out.printf("Acknowledging all %d messages pulled from the subscription.",
            ackIds.size());

        try {
          client.projects().subscriptions().acknowledge(subscriptionName,
              acknowledgeRequest).execute();
        } catch(IOException ex) {
          System.out.printf("Pubsub API returned error response while acknowledging received " +
              "messages:\n%s\n", ex);
          System.exit(1);
        }
      }
    }
  }

  public static void main(String[] args) {
    ArgumentParser parser = ArgumentParsers.newFor("PullWatchedCreativesSubscription")
        .build()
        .defaultHelp(true)
        .description(("Pulls creative status changes (if any) from a specified Google Cloud " +
            "Pub/Sub subscription."));
    parser.addArgument("-s", "--subscription_name")
        .help("The Google Cloud Pub/Sub subscription to be pulled. This value would be returned " +
            "in the response from the bidders.creatives.watch method, and should be provided " +
            "as-is in the form: " +
            "\"projects/realtimebidding-pubsub/subscriptions/{subscription_id}\"")
        .required(true);
    parser.addArgument("-m", "--max_messages")
        .help("The maximum number of messages to be returned in a single pull.")
        .type(Integer.class)
        .setDefault(Utils.getMaximumPageSize());
    parser.addArgument("-a", "--acknowledge")
        .help("'Whether to acknowledge the messages pulled from the subscription. Acknowledged " +
            "messages won't appear in subsequent responses to pulls from the subscription.'")
        .type(Boolean.class)
        .action(storeTrue())
        .setDefault(false);

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    Pubsub client = null;
    try {
      client = Utils.getPubsubClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create Pubsub API service:\n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:\n%s", ex);
      System.exit(1);
    }

    execute(client, parsedArgs);
  }
}

PHP

<?php

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

namespace Google\Ads\AuthorizedBuyers\RealTimeBidding\Examples\V1\Bidders_Creatives;

use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\BaseExample;
use Google\Ads\AuthorizedBuyers\RealTimeBidding\ExampleUtil\Config;
use Google_Service_Pubsub_AcknowledgeRequest;
use Google_Service_Pubsub_PullRequest;

/**
 * Enables monitoring of changes in status of a given bidder's creatives.
 *
 * Watched creatives will have changes to their status posted to Google Cloud Pub/Sub. For more
 * details on Google Cloud Pub/Sub, see:
 * https://cloud.google.com/pubsub/docs
 *
 * For an example of pulling creative status changes from a Google Cloud Pub/Sub subscription, see
 * PullWatchedCreativesSubscription.php.
 */
class PullWatchedCreativesSubscription extends BaseExample
{

    public function __construct($client)
    {
        $this->service = Config::getGoogleServicePubSub($client);
    }

    /**
     * @see BaseExample::getInputParameters()
     */
    protected function getInputParameters()
    {
        return [
            [
                'name' => 'subscription_name',
                'display' => 'Subscription name',
                'required' => true,
                'description' =>
                    'The Google Cloud Pub/Sub subscription to be pulled. This value would be ' .
                    'returned in the response from the bidders.creatives.watch method, and ' .
                    'should be provided as-is in the form:</br>' .
                    '"projects/realtimebidding-pubsub/subscriptions/{subscription_id}"'
            ],
            [
                'name' => 'acknowledge',
                'display' => 'Acknowledge',
                'required' => false,
                'description' =>
                    'A boolean describing whether to acknowledge the messages pulled from the ' .
                    'subscription. Acknowledged messages won\'t appear in subsequent responses ' .
                    'to pulls from the subscription.',
                'default' => 'false'
            ]
        ];
    }

    /**
     * @see BaseExample::run()
     */
    public function run()
    {
        $values = $this->formValues;

        $subscriptionName = $values['subscription_name'];
        $acknowledge = filter_var($values['acknowledge'], FILTER_VALIDATE_BOOLEAN);

        $pullRequest = new Google_Service_Pubsub_PullRequest();
        $pullRequest->maxMessages = 10;

        $ackIds = [];

        try {
            $response = $this->service->projects_subscriptions->pull($subscriptionName, $pullRequest);
            print "<h2>Pulled subscription '$subscriptionName' with results:</h2>";

            if (empty($response['receivedMessages'])) {
                print '<p>No messages received from the subscription.</p>';
                return;
            } else {
                print '<ul>';
                foreach ($response['receivedMessages'] as $receivedMessage) {
                    $ackIds[] = $receivedMessage['ackId'];
                    $message = $receivedMessage['message'];
                    $accountId = $message['attributes']['accountId'];
                    $creativeId = $message['attributes']['creativeId'];
                    $creativeServingDecision = $this->getPrettyPrintCreativeServingDecision(
                        $message['data']
                    );

                    print "<li>Creative found for buyer account ID '$accountId' with creative " .
                        "ID '$creativeId' has been updated with the following creative status:";

                    print '</br>';
                    print "<pre>$creativeServingDecision</pre>";
                    print '</li>';
                }
                print '</ul>';
            }
        } catch (Google_Service_Exception $ex) {
            if ($ex->getCode() === 404 || $ex->getCode() === 403) {
                print '<h1>Subscription not found or don\'t have access.</h1>';
            } else {
                throw $ex;
            }
        }

        if ($acknowledge) {
            $ackRequest = new Google_Service_Pubsub_AcknowledgeRequest();
            $ackRequest->ackIds = $ackIds;

            try {
                $ackResponse = $this->service->projects_subscriptions->acknowledge(
                    $subscriptionName,
                    $ackRequest
                );
                printf('Acknowledged %d messages pulled from the subscription.', count($ackIds));
                print '</br></br>';
            } catch (Google_Service_Exception $ex) {
                if ($ex->getCode() === 404 || $ex->getCode() === 403) {
                    print '<h1>AckIDs not found or do not have access.</h1>';
                } else {
                    throw $ex;
                }
            }
        }
    }

    /**
     * @see BaseExample::getName()
     */
    public function getName()
    {
        return 'Pull Watched Creatives Subscription';
    }

    public function getPrettyPrintCreativeServingDecision($data)
    {
        return json_encode(json_decode(base64_decode($data)), JSON_PRETTY_PRINT);
    }
}

Python

#!/usr/bin/python
#
# Copyright 2020 Google Inc. All Rights Reserved.
#
# 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.

"""Pulls creative status updates from a Google Cloud Pub/Sub subscription.

Note that messages do not expire until they are acknowledged; set the
acknowledged argument to True to acknowledge receiving all messages sent in the
response.

To learn more about Google Cloud Pub/Sub, read the developer documentation:
https://cloud.google.com/pubsub/docs/overview
https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions/list
https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions/acknowledge
"""


import argparse
import base64
import json
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError
import util


def main(pubsub, args):
  subscription_name = args.subscription_name

  print(f'Retrieving messages from subscription: "{subscription_name}"')

  body = {'maxMessages': args.max_messages}

  subscriptions = pubsub.projects().subscriptions().pull(
      subscription=subscription_name, body=body).execute()

  pprint.pprint(subscriptions)

  if 'receivedMessages' in subscriptions:
    ack_ids = []

    for received_message in subscriptions['receivedMessages']:
      ack_ids.append(received_message['ackId'])
      message = received_message['message']
      account_id = message['attributes']['accountId']
      creative_id = message['attributes']['creativeId']

      print(f'* Creative found for buyer account ID "{account_id}" with '
            f'creative ID "{creative_id}" has been updated with the following '
            'creative status:')
      creative_serving_decision = parse_creative_serving_decision(
          message['data'])
      pprint.pprint(creative_serving_decision)
      print()

    if args.acknowledge:
      body = {'ackIds': ack_ids}

      print(f'Acknowledging all {len(ack_ids)} messages pulled from the '
            'subscription.')

      pubsub.projects().subscriptions().acknowledge(
          subscription=subscription_name, body=body).execute()
  else:
    print('No messages received from the subscription.')


def parse_creative_serving_decision(data):
  """Parses the Creative Serving Decision from the Cloud Pub/Sub response.

  Args:
    data: a base64-encoded JSON string representing a creative's
          CreativeServingDevision.

  Returns:
    A JSON representation of the creative's CreativeServingDecision.
  """
  return json.loads(base64.b64decode(data))


if __name__ == '__main__':
  try:
    service = util.GetCloudPubSubService(version='v1')
  except IOError as ex:
    print(f'Unable to create pubsub service - {ex}')
    print('Did you specify the key file in util.py?')
    sys.exit(1)

  parser = argparse.ArgumentParser(
      description=('Pulls creative status changes (if any) from a specified '
                   'Google Cloud Pub/Sub subscription.'))

  # Required fields.
  parser.add_argument(
      '-s', '--subscription_name', required=True, type=str,
      help=('The Google Cloud Pub/Sub subscription to be pulled. This value '
            'would be returned in the response from the '
            'bidders.creatives.watch method, and should be provided as-is in '
            'the form: "projects/realtimebidding-pubsub/subscriptions/'
            '{subscription_id}"))'))
  parser.add_argument(
      '-m', '--max_messages', default=100, type=int,
      help='The maximum number of messages to be returned in a single pull.')
  parser.add_argument(
      '-a', '--acknowledge', default=False, type=bool,
      help=('Whether to acknowledge the messages pulled from the '
            'subscription. Acknowledged messages won\'t appear in subsequent '
            'responses to pulls from the subscription.'))

  args = parser.parse_args()

  main(service, args)


Ruby

#!/usr/bin/env ruby
# Encoding: utf-8
#
# Copyright:: Copyright 2020 Google LLC
#
# License:: 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.
#
# Pulls creative status updates from a Google Cloud Pub/Sub subscription.
#
# Note that messages do not expire until they are acknowledged; set the acknowledged argument to true to acknowledge
# receiving all messages sent in the response.
#
# To learn more about Google Cloud Pub/Sub, read the developer documentation:
# https://cloud.google.com/pubsub/docs/overview
# https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions/list
# https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.subscriptions/acknowledge

require 'base64'
require 'json'
require 'optparse'

require_relative '../../../util'


def pull_watched_creatives_subscription(pubsub, options)
  subscription_name = options[:subscription_name]
  pull_request_object = Google::Apis::PubsubV1::PullRequest.new(max_messages: options[:max_messages])

  puts "Retrieving messages from subscription '#{subscription_name}':"

  response = pubsub.pull_subscription(subscription_name, pull_request_object)

  unless response.received_messages.nil?
    ack_ids = []
    response.received_messages.each do |received_message|
      message = received_message.message
      account_id = message.attributes['accountId']
      creative_id = message.attributes['creativeId']
      ack_ids << received_message.ack_id
      creative_serving_decision = JSON.parse(message.data)

      puts "* Creative found for buyer account ID '#{account_id}' with creative ID '#{creative_id}' has been "\
           "updated with the following creative status:"
      puts JSON.pretty_generate(creative_serving_decision)

      if options[:acknowledge]
        ack_req_object = Google::Apis::PubsubV1::AcknowledgeRequest.new(ack_ids: ack_ids)

        puts "Acknowledging all #{ack_ids.length} messages pulled from the subscription."

        pubsub.acknowledge_subscription(subscription_name, ack_req_object)
      end
    end
  else
    puts 'No messages received from the subscription.'
  end
end


if __FILE__ == $0
  begin
    # Retrieve the service used to make API requests.
    service = get_cloud_pub_sub_service()
  rescue ArgumentError => e
    raise 'Unable to create service, with error message: #{e.message}'
  rescue Signet::AuthorizationError => e
    raise ('Unable to create service, was the KEY_FILE in util.rb set? ' +
           'Error message: #{e.message}')
  end

  # Set options and default values for fields used in this example.
  options = [
    Option.new(
      'subscription_name',
      'The Google Cloud Pub/Sub subscription to be pulled. This value would be returned in the response from the '\
      'bidders.creatives.watch method, and should be provided as-is in the form:'\
      'projects/realtimebidding-pubsub/subscriptions/{subscription_id}',
      short_alias: 's', required: true, default_value: nil
    ),
    Option.new(
      'max_messages',
      'The maximum number of messages to be returned in a single pull.',
      type: Integer, short_alias: 'm', required: false, default_value: 100
    ),
    Option.new(
      'acknowledge',
      'Whether to acknowledge the messages pulled from the subscription. Acknowledged messages won\'t appear in '\
      'subsequent responses to pulls from the subscription. By default, this sample will not acknowledge messages '\
      'pulled from the subscription.',
      type: FalseClass, short_alias: 'a', required: false, default_value: false
    ),
  ]

  # Parse options.
  parser = Parser.new(options)
  opts = parser.parse(ARGV)

  begin
    pull_watched_creatives_subscription(service, opts)
  rescue Google::Apis::ServerError => e
    raise "The following server error occured:\n#{e.message}"
  rescue Google::Apis::ClientError => e
    raise "Invalid client request:\n#{e.message}"
  rescue Google::Apis::AuthorizationError => e
    raise "Authorization error occured:\n#{e.message}"
  end
end