Responsive Search Ads Code Example

This example demonstrates how to setup Responsive Search Ads for a search advertising campaign.

Tip

Use the language selector in the documentation header to choose C#, Java, Php, or Python.

To get access and refresh tokens for your Microsoft Advertising user and make your first service call using the Bing Ads API, see the Quick Start sample. You'll want to review the Get Started guide and walkthroughs for your preferred language e.g., C#, Java, Php, and Python.

Supporting files for C#, Java, Php, and Python examples are available at GitHub. You can clone each repository or repurpose snippets as needed.

using System;
using System.Linq;
using System.ServiceModel;
using System.Threading.Tasks;
using Microsoft.BingAds.V13.CampaignManagement;
using Microsoft.BingAds;

namespace BingAdsExamplesLibrary.V13
{
    /// <summary>
    /// How to add responsive search ads in a new ad group.
    /// </summary>
    public class ResponsiveSearchAds : ExampleBase
    {
        public override string Description
        {
            get { return "Responsive Search Ads | Campaign Management V13"; }
        }

        public async override Task RunAsync(AuthorizationData authorizationData)
        {
            try
            {
                ApiEnvironment environment = ((OAuthDesktopMobileAuthCodeGrant)authorizationData.Authentication).Environment;

                CampaignManagementExampleHelper CampaignManagementExampleHelper = new CampaignManagementExampleHelper(
                    OutputStatusMessageDefault: this.OutputStatusMessage);
                CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
                    authorizationData: authorizationData,
                    environment: environment);

                // Create a Search campaign with one ad group and a responsive search ad.

                var campaigns = new[]{
                    new Campaign
                    {
                        Name = "Women's Shoes " + DateTime.UtcNow,                      
                        BudgetId = null,
                        DailyBudget = 50,
                        BudgetType = BudgetLimitType.DailyBudgetStandard,
                        Languages = new string[] { "All"},
                        TimeZone = "PacificTimeUSCanadaTijuana",
                    },
                };

                OutputStatusMessage("-----\nAddCampaigns:");
                AddCampaignsResponse addCampaignsResponse = await CampaignManagementExampleHelper.AddCampaignsAsync(
                    accountId: authorizationData.AccountId,
                    campaigns: campaigns);
                long?[] campaignIds = addCampaignsResponse.CampaignIds.ToArray();
                BatchError[] campaignErrors = addCampaignsResponse.PartialErrors.ToArray();
                OutputStatusMessage("CampaignIds:");
                CampaignManagementExampleHelper.OutputArrayOfLong(campaignIds);
                OutputStatusMessage("PartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchError(campaignErrors);

                // Add an ad group within the campaign.

                var adGroups = new[] {
                    new AdGroup
                    {
                        Name = "Women's Red Shoe Sale",
                        StartDate = null,
                        EndDate = new Date {
                            Month = 12,
                            Day = 31,
                            Year = DateTime.UtcNow.Year + 1
                        },
                        CpcBid = new Bid { Amount = 0.09 },
                    }
                };

                OutputStatusMessage("-----\nAddAdGroups:");
                AddAdGroupsResponse addAdGroupsResponse = await CampaignManagementExampleHelper.AddAdGroupsAsync(
                    campaignId: (long)campaignIds[0],
                    adGroups: adGroups,
                    returnInheritedBidStrategyTypes: false);
                long?[] adGroupIds = addAdGroupsResponse.AdGroupIds.ToArray();
                BatchError[] adGroupErrors = addAdGroupsResponse.PartialErrors.ToArray();
                OutputStatusMessage("AdGroupIds:");
                CampaignManagementExampleHelper.OutputArrayOfLong(adGroupIds);
                OutputStatusMessage("PartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchError(adGroupErrors);

                // Add keywords and ads within the ad group.

                var keywords = new[] {
                    new Keyword
                    {
                        Bid = new Bid { Amount = 0.47 },
                        Param2 = "10% Off",
                        MatchType = MatchType.Phrase,
                        Text = "Brand-A Shoes",
                    },
                };

                OutputStatusMessage("-----\nAddKeywords:");
                AddKeywordsResponse addKeywordsResponse = await CampaignManagementExampleHelper.AddKeywordsAsync(
                    adGroupId: (long)adGroupIds[0], 
                    keywords: keywords,
                    returnInheritedBidStrategyTypes: false);
                long?[] keywordIds = addKeywordsResponse.KeywordIds.ToArray();
                BatchError[] keywordErrors = addKeywordsResponse.PartialErrors.ToArray();
                OutputStatusMessage("KeywordIds:");
                CampaignManagementExampleHelper.OutputArrayOfLong(keywordIds);
                OutputStatusMessage("PartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchError(keywordErrors);

                // The responsive search ad descriptions and headlines are stored as text assets. 
                // You must set between 2-4 descriptions and 3-15 headlines.

                var ads = new Ad[] {
                    new ResponsiveSearchAd
                    {
                        Descriptions = new AssetLink []
                        {
                            new AssetLink
                            {
                                Asset = new TextAsset
                                {
                                    Text = "Find New Customers & Increase Sales!"
                                },
                                PinnedField = "Description1"
                            },
                            new AssetLink
                            {
                                Asset = new TextAsset
                                {
                                    Text = "Start Advertising on Contoso Today."
                                },
                                PinnedField = "Description2"
                            },
                        },
                        Headlines = new AssetLink []
                        {
                            new AssetLink
                            {
                                Asset = new TextAsset
                                {
                                    Text = "Contoso"
                                },
                                PinnedField = "Headline1"
                            },
                            new AssetLink
                            {
                                Asset = new TextAsset
                                {
                                    Text = "Quick & Easy Setup"
                                },
                                PinnedField = null
                            },
                            new AssetLink
                            {
                                Asset = new TextAsset
                                {
                                    Text = "Seemless Integration"
                                },
                                PinnedField = null
                            },
                        },
                        Path1 = "seattle",
                        Path2 = "shoe sale", 
                        FinalUrls = new[] {
                            "http://www.contoso.com/womenshoesale"
                        },
                    },                    
                };
                                
                OutputStatusMessage("-----\nAddAds:");
                AddAdsResponse addAdsResponse = await CampaignManagementExampleHelper.AddAdsAsync(
                    adGroupId: (long)adGroupIds[0], 
                    ads: ads);
                long?[] adIds = addAdsResponse.AdIds.ToArray();
                BatchError[] adErrors = addAdsResponse.PartialErrors.ToArray();
                OutputStatusMessage("AdIds:");
                CampaignManagementExampleHelper.OutputArrayOfLong(adIds);
                OutputStatusMessage("PartialErrors:");
                CampaignManagementExampleHelper.OutputArrayOfBatchError(adErrors);
                
                // Delete the campaign and everything it contains e.g., ad groups and ads.

                OutputStatusMessage("-----\nDeleteCampaigns:");
                await CampaignManagementExampleHelper.DeleteCampaignsAsync(
                    accountId: authorizationData.AccountId,
                    campaignIds: new[] { (long)campaignIds[0] });
                OutputStatusMessage(string.Format("Deleted Campaign Id {0}", campaignIds[0]));
            }
            // Catch authentication exceptions
            catch (OAuthTokenRequestException ex)
            {
                OutputStatusMessage(string.Format("Couldn't get OAuth tokens. Error: {0}. Description: {1}", ex.Details.Error, ex.Details.Description));
            }
            // Catch Campaign Management service exceptions
            catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.AdApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.Errors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.ApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (FaultException<Microsoft.BingAds.V13.CampaignManagement.EditorialApiFaultDetail> ex)
            {
                OutputStatusMessage(string.Join("; ", ex.Detail.OperationErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
                OutputStatusMessage(string.Join("; ", ex.Detail.BatchErrors.Select(error => string.Format("{0}: {1}", error.Code, error.Message))));
            }
            catch (Exception ex)
            {
                OutputStatusMessage(ex.Message);
            }
        }
    }
}
package com.microsoft.bingads.examples.v13;

import java.util.Calendar;

import com.microsoft.bingads.*;
import com.microsoft.bingads.v13.campaignmanagement.*;

public class ResponsiveSearchAds extends ExampleBase {
    
    public static void main(java.lang.String[] args) {
     
        try
        {
            authorizationData = getAuthorizationData(); 
             
            CampaignManagementExampleHelper.CampaignManagementService = new ServiceClient<ICampaignManagementService>(
                        authorizationData, 
                        API_ENVIRONMENT,
                        ICampaignManagementService.class);
            
            // Create a Search campaign with one ad group and a responsive search ad.

            ArrayOfCampaign campaigns = new ArrayOfCampaign();
            Campaign campaign = new Campaign();
            campaign.setBudgetType(BudgetLimitType.DAILY_BUDGET_STANDARD);
            campaign.setDailyBudget(50.00);
            ArrayOfstring languages = new ArrayOfstring();
            languages.getStrings().add("All");
            campaign.setLanguages(languages);
            campaign.setName("Women's Shoes " + System.currentTimeMillis());
            campaign.setTimeZone("PacificTimeUSCanadaTijuana");
            campaigns.getCampaigns().add(campaign);

            outputStatusMessage("-----\nAddCampaigns:");
            AddCampaignsResponse addCampaignsResponse = CampaignManagementExampleHelper.addCampaigns(
                    authorizationData.getAccountId(), 
                    campaigns);            
            ArrayOfNullableOflong campaignIds = addCampaignsResponse.getCampaignIds();
            ArrayOfBatchError campaignErrors = addCampaignsResponse.getPartialErrors();
            outputStatusMessage("CampaignIds:");
            CampaignManagementExampleHelper.outputArrayOfNullableOflong(campaignIds);
            outputStatusMessage("PartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchError(campaignErrors);

            // Add an ad group within the campaign.
            
            ArrayOfAdGroup adGroups = new ArrayOfAdGroup();
            AdGroup adGroup = new AdGroup();
            adGroup.setName("Women's Red Shoe Sale");
            adGroup.setStartDate(null);
            Calendar calendar = Calendar.getInstance();
            adGroup.setEndDate(new com.microsoft.bingads.v13.campaignmanagement.Date());
            adGroup.getEndDate().setDay(31);
            adGroup.getEndDate().setMonth(12);
            adGroup.getEndDate().setYear(calendar.get(Calendar.YEAR));
            Bid CpcBid = new Bid();
            CpcBid.setAmount(0.09);
            adGroup.setCpcBid(CpcBid);
            adGroups.getAdGroups().add(adGroup);

            outputStatusMessage("-----\nAddAdGroups:");
            AddAdGroupsResponse addAdGroupsResponse = CampaignManagementExampleHelper.addAdGroups(
                    campaignIds.getLongs().get(0), 
                    adGroups, 
                    false);
            ArrayOfNullableOflong adGroupIds = addAdGroupsResponse.getAdGroupIds();
            ArrayOfBatchError adGroupErrors = addAdGroupsResponse.getPartialErrors();
            outputStatusMessage("AdGroupIds:");
            CampaignManagementExampleHelper.outputArrayOfNullableOflong(adGroupIds);
            outputStatusMessage("PartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchError(adGroupErrors); 

            // Add keywords and ads within the ad group.
            
            ArrayOfKeyword keywords = new ArrayOfKeyword();
            Keyword keyword = new Keyword();
            keyword.setBid(new Bid());
            keyword.getBid().setAmount(0.47);
            keyword.setParam2("10% Off");
            keyword.setMatchType(MatchType.PHRASE);
            keyword.setText("Brand-A Shoes");
            keywords.getKeywords().add(keyword);

            outputStatusMessage("-----\nAddKeywords:");
            AddKeywordsResponse addKeywordsResponse = CampaignManagementExampleHelper.addKeywords(
                    adGroupIds.getLongs().get(0), 
                    keywords, 
                    false);
            ArrayOfNullableOflong keywordIds = addKeywordsResponse.getKeywordIds();
            ArrayOfBatchError keywordErrors = addKeywordsResponse.getPartialErrors();
            outputStatusMessage("KeywordIds:");
            CampaignManagementExampleHelper.outputArrayOfNullableOflong(keywordIds);
            outputStatusMessage("PartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchError(keywordErrors);

            // The responsive search ad descriptions and headlines are stored as text assets. 
            // You must set between 2-4 descriptions and 3-15 headlines.
            
            ArrayOfAd ads = new ArrayOfAd();
            ResponsiveSearchAd responsiveSearchAd = new ResponsiveSearchAd();            
            ArrayOfAssetLink descriptionAssetLinks = new ArrayOfAssetLink();
            AssetLink descriptionAssetLinkA = new AssetLink();
            TextAsset descriptionTextAssetA = new TextAsset();
            descriptionTextAssetA.setText("Find New Customers & Increase Sales!");
            descriptionAssetLinkA.setAsset(descriptionTextAssetA);
            descriptionAssetLinkA.setPinnedField("Description1");
            descriptionAssetLinks.getAssetLinks().add(descriptionAssetLinkA);
            AssetLink descriptionAssetLinkB = new AssetLink();
            TextAsset descriptionTextAssetB = new TextAsset();
            descriptionTextAssetB.setText("Start Advertising on Contoso Today.");
            descriptionAssetLinkB.setAsset(descriptionTextAssetB);
            descriptionAssetLinkB.setPinnedField("Description2");
            descriptionAssetLinks.getAssetLinks().add(descriptionAssetLinkB);
            responsiveSearchAd.setDescriptions(descriptionAssetLinks);
            ArrayOfAssetLink headlineAssetLinks = new ArrayOfAssetLink();
            AssetLink headlineAssetLinkA = new AssetLink();
            TextAsset headlineTextAssetA = new TextAsset();
            headlineTextAssetA.setText("Contoso");
            headlineAssetLinkA.setAsset(headlineTextAssetA);
            headlineAssetLinkA.setPinnedField("Headline1");
            headlineAssetLinks.getAssetLinks().add(headlineAssetLinkA);
            AssetLink headlineAssetLinkB = new AssetLink();
            TextAsset headlineTextAssetB = new TextAsset();
            headlineTextAssetB.setText("Quick & Easy Setup");
            headlineAssetLinkB.setAsset(headlineTextAssetB);
            headlineAssetLinkB.setPinnedField(null);
            headlineAssetLinks.getAssetLinks().add(headlineAssetLinkB);
            AssetLink headlineAssetLinkC = new AssetLink();
            TextAsset headlineTextAssetC = new TextAsset();
            headlineTextAssetC.setText("Seemless Integration");
            headlineAssetLinkC.setAsset(headlineTextAssetC);
            headlineAssetLinkC.setPinnedField(null);
            headlineAssetLinks.getAssetLinks().add(headlineAssetLinkC);
            responsiveSearchAd.setHeadlines(headlineAssetLinks);
            responsiveSearchAd.setPath1("seattle");
            responsiveSearchAd.setPath2("shoe sale");
            com.microsoft.bingads.v13.campaignmanagement.ArrayOfstring finalUrls = new com.microsoft.bingads.v13.campaignmanagement.ArrayOfstring();
            finalUrls.getStrings().add("http://www.contoso.com/womenshoesale");
            responsiveSearchAd.setFinalUrls(finalUrls);
            ads.getAds().add(responsiveSearchAd);

            outputStatusMessage("-----\nAddAds:");
            AddAdsResponse addAdsResponse = CampaignManagementExampleHelper.addAds(
                    adGroupIds.getLongs().get(0), 
                    ads);
            ArrayOfNullableOflong adIds = addAdsResponse.getAdIds();
            ArrayOfBatchError adErrors = addAdsResponse.getPartialErrors();
            outputStatusMessage("AdIds:");
            CampaignManagementExampleHelper.outputArrayOfNullableOflong(adIds);
            outputStatusMessage("PartialErrors:");
            CampaignManagementExampleHelper.outputArrayOfBatchError(adErrors);

            // Delete the campaign and everything it contains e.g., ad groups and ads.

            outputStatusMessage("-----\nDeleteCampaigns:");
            ArrayOflong deleteCampaignIds = new ArrayOflong();
            deleteCampaignIds.getLongs().add(campaignIds.getLongs().get(0));
            CampaignManagementExampleHelper.deleteCampaigns(
                    authorizationData.getAccountId(), 
                    deleteCampaignIds);
            outputStatusMessage(String.format("Deleted CampaignId %d", deleteCampaignIds.getLongs().get(0))); 
        } 
        catch (Exception ex) {
            String faultXml = ExampleExceptionHelper.getBingAdsExceptionFaultXml(ex, System.out);
            outputStatusMessage(faultXml);
            String message = ExampleExceptionHelper.handleBingAdsSDKException(ex, System.out);
            outputStatusMessage(message);
        }
    }    
 }
<?php

namespace Microsoft\BingAds\Samples\V13;

// For more information about installing and using the Bing Ads PHP SDK, 
// see https://go.microsoft.com/fwlink/?linkid=838593.

require_once __DIR__ . "/../vendor/autoload.php";

include __DIR__ . "/AuthHelper.php";
include __DIR__ . "/CampaignManagementExampleHelper.php";

use SoapVar;
use SoapFault;
use Exception;

//Specify the Microsoft\BingAds\V13\CampaignManagement classes that will be used.
use Microsoft\BingAds\V13\CampaignManagement\Campaign;
use Microsoft\BingAds\V13\CampaignManagement\AdGroup;
use Microsoft\BingAds\V13\CampaignManagement\Keyword;
use Microsoft\BingAds\V13\CampaignManagement\Ad;
use Microsoft\BingAds\V13\CampaignManagement\AdType;
use Microsoft\BingAds\V13\CampaignManagement\ResponsiveSearchAd;
use Microsoft\BingAds\V13\CampaignManagement\AssetLink;
use Microsoft\BingAds\V13\CampaignManagement\ImageAsset;
use Microsoft\BingAds\V13\CampaignManagement\Bid;
use Microsoft\BingAds\V13\CampaignManagement\MatchType;
use Microsoft\BingAds\V13\CampaignManagement\BudgetLimitType;
use Microsoft\BingAds\V13\CampaignManagement\Date;

// Specify the Microsoft\BingAds\Auth classes that will be used.
use Microsoft\BingAds\Auth\ServiceClient;
use Microsoft\BingAds\Auth\ServiceClientType;

// Specify the Microsoft\BingAds\Samples classes that will be used.
use Microsoft\BingAds\Samples\V13\AuthHelper;
use Microsoft\BingAds\Samples\V13\CampaignManagementExampleHelper;
    
try
{
    // Authenticate user credentials and set the account ID for the sample.  
    AuthHelper::Authenticate();
                
    // Create a Search campaign with one ad group and a responsive search ad.
    
    $campaigns = array();   
    $campaign = new Campaign();
    $campaign->Name = "Women's Shoes " . $_SERVER['REQUEST_TIME'];
    $campaign->BudgetType = BudgetLimitType::DailyBudgetStandard;
    $campaign->DailyBudget = 50.00;
    $campaign->Languages = array("All");
    $campaign->TimeZone = "PacificTimeUSCanadaTijuana";
    $campaigns[] = $campaign;
    
    print("-----\r\nAddCampaigns:\r\n");
    $addCampaignsResponse = CampaignManagementExampleHelper::AddCampaigns(
        $GLOBALS['AuthorizationData']->AccountId, 
        $campaigns
    );
    $campaignIds = $addCampaignsResponse->CampaignIds;
    print("CampaignIds:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfLong($campaignIds);
    print("PartialErrors:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfBatchError($addCampaignsResponse->PartialErrors);
    
    // Add an ad group within the campaign.

    $adGroups = array();
    $adGroup = new AdGroup();
    $adGroup->CpcBid = new Bid();
    $adGroup->CpcBid->Amount = 0.09;
    date_default_timezone_set('UTC');
    $endDate = new Date();
    $endDate->Day = 31;
    $endDate->Month = 12;
    $endDate->Year = date("Y");
    $adGroup->EndDate = $endDate;
    $adGroup->Name = "Women's Red Shoe Sale";    
    $adGroup->StartDate = null;    
    $adGroups[] = $adGroup;
 
    print("-----\r\nAddAdGroups:\r\n");
    $addAdGroupsResponse = CampaignManagementExampleHelper::AddAdGroups(
        $campaignIds->long[0], 
        $adGroups,
        null
    );
    $adGroupIds = $addAdGroupsResponse->AdGroupIds;
    print("AdGroupIds:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfLong($adGroupIds);
    print("PartialErrors:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfBatchError($addAdGroupsResponse->PartialErrors);
    
    // Add keywords and ads within the ad group.

    $keywords = array();
    $keyword = new Keyword();
    $keyword->Bid = new Bid();
    $keyword->Bid->Amount = 0.47;
    $keyword->Param2 = "10% Off";
    $keyword->MatchType = MatchType::Broad;
    $keyword->Text = "Brand-A Shoes";
    $keywords[] = $keyword;

    print("-----\r\nAddKeywords:\r\n");
    $addKeywordsResponse = CampaignManagementExampleHelper::AddKeywords(
        $adGroupIds->long[0], 
        $keywords,
        null
    );
    print("KeywordIds:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfLong($addKeywordsResponse->KeywordIds);
    print("PartialErrors:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfBatchError($addKeywordsResponse->PartialErrors);

    // The responsive search ad descriptions and headlines are stored as text assets. 
    // You must set between 2-4 descriptions and 3-15 headlines.
    
    $ads = array();
    $responsiveSearchAd = new ResponsiveSearchAd();
    $descriptionAssetLinks = array();
    $descriptionAssetLinkA = new AssetLink();
    $descriptionTextAssetA = new ImageAsset();
    $descriptionTextAssetA->Text = "Find New Customers & Increase Sales!";
    $descriptionAssetLinkA->Asset = new SoapVar(
        $descriptionTextAssetA, 
        SOAP_ENC_OBJECT, 
        'TextAsset', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );
    $descriptionAssetLinkA->PinnedField = "Description1";
    $descriptionAssetLinks[] = $descriptionAssetLinkA;
    $descriptionAssetLinkB = new AssetLink();
    $descriptionTextAssetB = new ImageAsset();
    $descriptionTextAssetB->Text = "Start Advertising on Contoso Today.";
    $descriptionAssetLinkB->Asset = new SoapVar(
        $descriptionTextAssetB, 
        SOAP_ENC_OBJECT, 
        'TextAsset', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );
    $descriptionAssetLinkB->PinnedField = "Description2";
    $descriptionAssetLinks[] = $descriptionAssetLinkB;
    $responsiveSearchAd->Descriptions = $descriptionAssetLinks;
    $headlineAssetLinks = array();
    $headlineAssetLinkA = new AssetLink();
    $headlineTextAssetA = new ImageAsset();
    $headlineTextAssetA->Text = "Contoso";
    $headlineAssetLinkA->Asset = new SoapVar(
        $headlineTextAssetA, 
        SOAP_ENC_OBJECT, 
        'TextAsset', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );
    $headlineAssetLinkA->PinnedField = "Headline1";
    $headlineAssetLinks[] = $headlineAssetLinkA;
    $headlineAssetLinkB = new AssetLink();
    $headlineTextAssetB = new ImageAsset();
    $headlineTextAssetB->Text = "Quick & Easy Setup";
    $headlineAssetLinkB->Asset = new SoapVar(
        $headlineTextAssetB, 
        SOAP_ENC_OBJECT, 
        'TextAsset', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );
    $headlineAssetLinkB->PinnedField = null;
    $headlineAssetLinks[] = $headlineAssetLinkB;
    $headlineAssetLinkC = new AssetLink();
    $headlineTextAssetC = new ImageAsset();
    $headlineTextAssetC->Text = "Seemless Integration";
    $headlineAssetLinkC->Asset = new SoapVar(
        $headlineTextAssetC, 
        SOAP_ENC_OBJECT, 
        'TextAsset', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );
    $headlineAssetLinkC->PinnedField = null;
    $headlineAssetLinks[] = $headlineAssetLinkC;
    $responsiveSearchAd->Headlines = $headlineAssetLinks;
    $responsiveSearchAd->Path1 = "seattle";
    $responsiveSearchAd->Path2 = "shoe sale";
    $responsiveSearchAd->FinalUrls = array("http://www.contoso.com/womenshoesale");
    $ads[] = new SoapVar(
        $responsiveSearchAd, 
        SOAP_ENC_OBJECT, 
        'ResponsiveSearchAd', 
        $GLOBALS['CampaignManagementProxy']->GetNamespace()
    );

    print("-----\r\nAddAds:\r\n");
    $addAdsResponse = CampaignManagementExampleHelper::AddAds(
        $adGroupIds->long[0], 
        $ads
    );
    print("AdIds:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfLong($addAdsResponse->AdIds);
    print("PartialErrors:\r\n");
    CampaignManagementExampleHelper::OutputArrayOfBatchError($addAdsResponse->PartialErrors);

    // Delete the campaign and everything it contains e.g., ad groups and ads.

    print("-----\r\nDeleteCampaigns:\r\n");
    CampaignManagementExampleHelper::DeleteCampaigns(
        $GLOBALS['AuthorizationData']->AccountId, 
        array($campaignIds->long[0])
    );
    printf("Deleted Campaign Id %s\r\n", $campaignIds->long[0]);
}
catch (SoapFault $e)
{
    printf("-----\r\nFault Code: %s\r\nFault String: %s\r\nFault Detail: \r\n", $e->faultcode, $e->faultstring);
    var_dump($e->detail);
    print "-----\r\nLast SOAP request/response:\r\n";
    print $GLOBALS['Proxy']->GetWsdl() . "\r\n";
    print $GLOBALS['Proxy']->GetService()->__getLastRequest()."\r\n";
    print $GLOBALS['Proxy']->GetService()->__getLastResponse()."\r\n";
}
catch (Exception $e)
{
    // Ignore fault exceptions that we already caught.
    if ($e->getPrevious())
    { ; }
    else
    {
        print $e->getCode()." ".$e->getMessage()."\n\n";
        print $e->getTraceAsString()."\n\n";
    }
}
from auth_helper import *
from campaignmanagement_example_helper import *

# You must provide credentials in auth_helper.py.

def main(authorization_data):

    try:
        # Create a Search campaign with one ad group and a responsive search ad.
                
        campaigns=campaign_service.factory.create('ArrayOfCampaign')
        campaign=set_elements_to_none(campaign_service.factory.create('Campaign'))
        campaign.BudgetType='DailyBudgetStandard'
        campaign.DailyBudget=50
        languages=campaign_service.factory.create('ns3:ArrayOfstring')
        languages.string.append('All')
        campaign.Languages=languages
        campaign.Name="Women's Shoes " + strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
        campaign.TimeZone='PacificTimeUSCanadaTijuana'
        campaigns.Campaign.append(campaign)

        output_status_message("-----\nAddCampaigns:")
        add_campaigns_response=campaign_service.AddCampaigns(
            AccountId=authorization_data.account_id,
            Campaigns=campaigns
        )
        campaign_ids={
            'long': add_campaigns_response.CampaignIds['long'] if add_campaigns_response.CampaignIds['long'] else None
        }
        output_status_message("CampaignIds:")
        output_array_of_long(campaign_ids)
        output_status_message("PartialErrors:")
        output_array_of_batcherror(add_campaigns_response.PartialErrors)
        
        # Add an ad group within the campaign.

        ad_groups=campaign_service.factory.create('ArrayOfAdGroup')
        ad_group=set_elements_to_none(campaign_service.factory.create('AdGroup'))
        ad_group.Name="Women's Red Shoe Sale"
        end_date=campaign_service.factory.create('Date')
        end_date.Day=31
        end_date.Month=12
        current_time=gmtime()
        end_date.Year=current_time.tm_year + 1
        ad_group.EndDate=end_date
        cpc_bid=campaign_service.factory.create('Bid')
        cpc_bid.Amount=0.09
        ad_group.CpcBid=cpc_bid
        ad_groups.AdGroup.append(ad_group)

        output_status_message("-----\nAddAdGroups:")
        add_ad_groups_response=campaign_service.AddAdGroups(
            CampaignId=campaign_ids['long'][0],
            AdGroups=ad_groups,
            ReturnInheritedBidStrategyTypes=False
        )
        ad_group_ids={
            'long': add_ad_groups_response.AdGroupIds['long'] if add_ad_groups_response.AdGroupIds['long'] else None
        }
        output_status_message("AdGroupIds:")
        output_array_of_long(ad_group_ids)
        output_status_message("PartialErrors:")
        output_array_of_batcherror(add_ad_groups_response.PartialErrors)

        # Add keywords and ads within the ad group.
        
        keywords=campaign_service.factory.create('ArrayOfKeyword')
        keyword=set_elements_to_none(campaign_service.factory.create('Keyword'))
        keyword.Bid=campaign_service.factory.create('Bid')
        keyword.Bid.Amount=0.47
        keyword.Param2='10% Off'
        keyword.MatchType='Broad'
        keyword.Text='Brand-A Shoes'
        keywords.Keyword.append(keyword)

        output_status_message("-----\nAddKeywords:")
        add_keywords_response=campaign_service.AddKeywords(
            AdGroupId=ad_group_ids['long'][0],
            Keywords=keywords,
            ReturnInheritedBidStrategyTypes=False
        )
        keyword_ids={
            'long': add_keywords_response.KeywordIds['long'] if add_keywords_response.KeywordIds else None
        }
        output_status_message("KeywordIds:")
        output_array_of_long(keyword_ids)
        output_status_message("PartialErrors:")
        output_array_of_batcherror(add_keywords_response.PartialErrors)

        # The responsive search ad descriptions and headlines are stored as text assets. 
        # You must set between 2-4 descriptions and 3-15 headlines.
        
        ads=campaign_service.factory.create('ArrayOfAd')
        responsive_search_ad=set_elements_to_none(campaign_service.factory.create('ResponsiveSearchAd'))
        description_asset_links=campaign_service.factory.create('ArrayOfAssetLink')
        description_asset_link_a=set_elements_to_none(campaign_service.factory.create('AssetLink'))
        description_text_asset_a=set_elements_to_none(campaign_service.factory.create('TextAsset'))
        description_text_asset_a.Text="Find New Customers & Increase Sales!"
        description_asset_link_a.Asset=description_text_asset_a
        description_asset_link_a.PinnedField="Description1"
        description_asset_links.AssetLink.append(description_asset_link_a)
        description_asset_link_b=set_elements_to_none(campaign_service.factory.create('AssetLink'))
        description_text_asset_b=set_elements_to_none(campaign_service.factory.create('TextAsset'))
        description_text_asset_b.Text="Start Advertising on Contoso Today."
        description_asset_link_b.Asset=description_text_asset_b
        description_asset_link_b.PinnedField="Description2"
        description_asset_links.AssetLink.append(description_asset_link_b)
        responsive_search_ad.Descriptions=description_asset_links
        headline_asset_links=campaign_service.factory.create('ArrayOfAssetLink')
        headline_asset_link_a=set_elements_to_none(campaign_service.factory.create('AssetLink'))
        headline_text_asset_a=set_elements_to_none(campaign_service.factory.create('TextAsset'))
        headline_text_asset_a.Text="Contoso"
        headline_asset_link_a.Asset=headline_text_asset_a
        headline_asset_link_a.PinnedField="Headline1"
        headline_asset_links.AssetLink.append(headline_asset_link_a)
        headline_asset_link_b=set_elements_to_none(campaign_service.factory.create('AssetLink'))
        headline_text_asset_b=set_elements_to_none(campaign_service.factory.create('TextAsset'))
        headline_text_asset_b.Text="Quick & Easy Setup"
        headline_asset_link_b.Asset=headline_text_asset_b
        headline_asset_link_b.PinnedField=None
        headline_asset_links.AssetLink.append(headline_asset_link_b)
        headline_asset_link_c=set_elements_to_none(campaign_service.factory.create('AssetLink'))
        headline_text_asset_c=set_elements_to_none(campaign_service.factory.create('TextAsset'))
        headline_text_asset_c.Text="Seemless Integration"
        headline_asset_link_c.Asset=headline_text_asset_c
        headline_asset_link_c.PinnedField=None
        headline_asset_links.AssetLink.append(headline_asset_link_c)
        responsive_search_ad.Headlines=headline_asset_links
        responsive_search_ad.Path1='seattle'
        responsive_search_ad.Path2='shoe sale'
        responsive_search_ad.Type='ResponsiveSearch'
        final_urls=campaign_service.factory.create('ns3:ArrayOfstring')
        final_urls.string.append('http://www.contoso.com/womenshoesale')
        responsive_search_ad.FinalUrls=final_urls
        ads.Ad.append(responsive_search_ad)
        
        output_status_message("-----\nAddAds:")
        add_ads_response=campaign_service.AddAds(
            AdGroupId=ad_group_ids['long'][0],
            Ads=ads
        )
        ad_ids={
            'long': add_ads_response.AdIds['long'] if add_ads_response.AdIds['long'] else None
        }
        output_status_message("AdIds:")
        output_array_of_long(ad_ids)
        output_status_message("PartialErrors:")
        output_array_of_batcherror(add_ads_response.PartialErrors)
        
        # Delete the campaign and everything it contains e.g., ad groups and ads.

        output_status_message("-----\nDeleteCampaigns:")
        campaign_service.DeleteCampaigns(
            AccountId=authorization_data.account_id,
            CampaignIds=campaign_ids
        )
        output_status_message("Deleted Campaign Id {0}".format(campaign_ids['long'][0]))

    except WebFault as ex:
        output_webfault_errors(ex)
    except Exception as ex:
        output_status_message(ex)

# Main execution
if __name__ == '__main__':

    print("Loading the web service client proxies...")
    
    authorization_data=AuthorizationData(
        account_id=None,
        customer_id=None,
        developer_token=DEVELOPER_TOKEN,
        authentication=None,
    )

    campaign_service=ServiceClient(
        service='CampaignManagementService', 
        version=13,
        authorization_data=authorization_data, 
        environment=ENVIRONMENT,
    )
        
    authenticate(authorization_data)
        
    main(authorization_data)

See Also

Get Started with the Bing Ads API