How to Add Campaigns in Python (V5.1)

Hello,

The Python example below shows how to create campaigns by using the Campaign Management Web service. This example assumes that you have already determined which account ID will be used for the campaigns; you must substitute your account ID for the accId variable that is assigned 489 in the following code.

We'd like to get your feedback on this Python example as we prepare other Python examples for release to MSDN. Post a comment below if you feel this example is helpful or requires modification.

Thank you,

Walter Poupore
Developer Content Manager
Microsoft adCenter API

# This program requires the following Python modules:
#  1. ElementTree toolkit (https://effbot.org/downloads/\#elementtree) for
#     XML generation or document loading in Python

import elementtree.ElementTree as ET
import httplib

accId = 489

# Use either the sandbox or production host.
# This example is for the sandbox host.
host = "sandboxapi.adcenter.microsoft.com"
# The following commented-out line contains the production host.
# host = "adcenterapi.microsoft.com"

# The Web service URI, proxy, and service operation definitions.
URI = "https://" + host + "/api/advertiser/v5.1/"
campaignProxy = URI + "CampaignManagement/CampaignManagementService.svc?wsdl"
action = "AddCampaigns"

# Namespace definitions.
ns_soapenv = "https://schemas.xmlsoap.org/soap/envelope/"
ns_xsd = "https://www.w3.org/1999/XMLSchema"
ns_xsi = "https://www.w3.org/1999/XMLSchema-instance"
ns_soapenc = "https://schemas.xmlsoap.org/soap/encoding/"
ns_arrays = "https://schemas.microsoft.com/2003/10/Serialization/Arrays"
ns_adCenter = "https://adcenter.microsoft.com/api/advertiser/v5"

# Set up the namespace prefix mappings.
ET._namespace_map[ns_soapenv] = 'SOAP-ENV'
ET._namespace_map[ns_xsd] = 'xsd'
ET._namespace_map[ns_xsi] = 'xsi'
ET._namespace_map[ns_soapenc] = 'SOAP-ENC'

# This method programmatically constructs a SOAP envelope containing the
# AddCampaigns request.
def createSoapRequest(username, password, devtoken):

    # Create the root element.
    root = ET.Element("{" + ns_soapenv + "}Envelope")
    root.attrib["xmlns:xsd"] = ns_xsd
    root.attrib["xmlns:xsi"] = ns_xsi
    root.attrib["xmlns:SOAP-ENC"] = ns_soapenc
    root.attrib["SOAP-ENV:encodingStyle"] = ns_soapenv

    # Create the header element.
    header = ET.SubElement(root,"{" + ns_soapenv + "}Header")

    # Add in the developer token.
    devToken = ET.SubElement(header,"DeveloperToken")
    devToken.attrib["xmlns"] = ns_adCenter
    devTokenValue = ET.SubElement(devToken,"Value")
    devTokenValue.text = devtoken

    # Add in the user credentials.
    userCreds = ET.SubElement(header,"UserCredentials")
    userCreds.attrib["xmlns"] = ns_adCenter
    ucPassword = ET.SubElement(userCreds,"Password")
    ucPassword.text = password
    ucUsername = ET.SubElement(userCreds,"Username")
    ucUsername.text = username

    # Add in the application token.
    appToken = ET.SubElement(header,"ApplicationToken")
    appToken.attrib["xmlns"] = ns_adCenter
    appTokenValue = ET.SubElement(appToken,"Value")

    # Create the body element.
    body = ET.SubElement(root,"{" + ns_soapenv + "}Body")

    # Create the AddCampaignsRequest element.
    addCampaignsRequest = ET.SubElement(body,"AddCampaignsRequest")
    addCampaignsRequest.attrib["xmlns"] = ns_adCenter

    # Add in the account ID.
    accountId = ET.SubElement(addCampaignsRequest,"AccountId")
    accountId.attrib["xmlns"] = ns_adCenter
    accountId.text = str(accId)

    # Create the Campaigns element.
    campaigns = ET.SubElement(addCampaignsRequest,"Campaigns")
    campaigns.attrib["xmlns"] = ns_adCenter

    # Create two Campaign elements.
    # campaign0 is the first Campaign element.
    campaign0 = ET.SubElement(campaigns,"Campaign")
    campaign0.attrib["xmlns"] = ns_adCenter
    campaign0BudgetType = ET.SubElement(campaign0,"BudgetType")
    campaign0BudgetType.text = "MonthlyBudgetSpendUntilDepleted"
    campaign0ConversionTrackingEnabled = ET.SubElement(campaign0,"ConversionTrackingEnabled")
    campaign0ConversionTrackingEnabled.text = "false"
    campaign0DaylightSaving = ET.SubElement(campaign0,"DaylightSaving")
    campaign0DaylightSaving.text = "true"
    campaign0Description = ET.SubElement(campaign0,"Description")
    campaign0Description.text = "Winter Clothing Products"
    campaign0MonthlyBudget = ET.SubElement(campaign0,"MonthlyBudget")
    campaign0MonthlyBudget.text = "50000.00"
    campaign0Name = ET.SubElement(campaign0,"Name")
    campaign0Name.text = "Winter Clothing"
    campaign0TimeZone = ET.SubElement(campaign0,"TimeZone")
    campaign0TimeZone.text = "EasternTimeUSCanada"
    # campaign1 is the second Campaign element.
    campaign1 = ET.SubElement(campaigns,"Campaign")
    campaign1.attrib["xmlns"] = ns_adCenter
    campaign1BudgetType = ET.SubElement(campaign1,"BudgetType")
    campaign1BudgetType.text = "MonthlyBudgetSpendUntilDepleted"
    campaign1ConversionTrackingEnabled = ET.SubElement(campaign1,"ConversionTrackingEnabled")
    campaign1ConversionTrackingEnabled.text = "false"
    campaign1DaylightSaving = ET.SubElement(campaign1,"DaylightSaving")
    campaign1DaylightSaving.text = "true"
    campaign1Description = ET.SubElement(campaign1,"Description")
    campaign1Description.text = "Athletic gear for winter"
    campaign1MonthlyBudget = ET.SubElement(campaign1,"MonthlyBudget")
    campaign1MonthlyBudget.text = "40000.00"
    campaign1Name = ET.SubElement(campaign1,"Name")
    campaign1Name.text = "Winter Athletic Gear"
    campaign1TimeZone = ET.SubElement(campaign1,"TimeZone")
    campaign1TimeZone.text = "EasternTimeUSCanada"

    return root

# Create a web service client and execute the AddCampaigns method
def createCampaigns(username,password,devtoken):

    soapRequest = createSoapRequest( username, password, devtoken)
    soapStr = ET.tostring(soapRequest)

    # Create the webservice client and add required headers.
    webservice = httplib.HTTPS(host)
    webservice.putrequest("POST", campaignProxy)
    webservice.putheader("Accept","text/xml")
    webservice.putheader("Accept","multipart/*");
    webservice.putheader("Content-type", "text/xml; charset=\"UTF-8\"")
    webservice.putheader("Content-length", "%d" % len(soapStr))
    webservice.putheader("SOAPAction", action)
    webservice.endheaders()

    # Execute the web service request.
    webservice.send(soapStr)

    # Get the response message and results.
    statuscode, statusmessage, header = webservice.getreply()
    #print "Response: ", statuscode, statusmessage # Can print for debug purposes.
    #print "Return headers: ", header # Can print for debug purposes.

    res = webservice.getfile().read()

    if statusmessage == "OK":

        # The campaigns were successfully added.
        print action + " succeeded."

        # Display the adCenter tracking ID.
        responseTree = ET.fromstring(res)
        print "Tracking ID: " + responseTree.findtext(".//{" + ns_adCenter + "}TrackingId")

        # Print out the campaign IDs.
        print "The following campaign IDs were returned by " + action + ":"
        campaignList = responseTree.findall(".//{" + ns_arrays + "}int")
        for campaign in campaignList:
            print "Campaign ID: " + campaign.text

    else:

        # Error(s) were encountered.
        print action + " failed."
        faultTree = ET.fromstring(res)
        print faultTree.findtext(".//faultcode") + " " + faultTree.findtext(".//faultstring")
        print "TrackingId: " + faultTree.findtext(".//{" + ns_adCenter + "}TrackingId")

        # Display the adCenter operation errors.
        operationErrorList = faultTree.findall(".//{" + ns_adCenter + "}OperationError")
        for i in range(len(operationErrorList)):
            print "Operation error " + operationErrorList[i].findtext("./{" + ns_adCenter + "}Code") + " encountered."
            print operationErrorList[i].findtext("./{" + ns_adCenter + "}Message")

        # Display batch errors.
        batchErrorList = faultTree.findall(".//{" + ns_adCenter + "}BatchError")
        for i in range(len(batchErrorList)):
            print "Campaign index " + str(i)
            print "Batch error " + batchErrorList[i].findtext("./{" + ns_adCenter + "}Code") + " encountered."
            print batchErrorList[i].findtext("./{" + ns_adCenter + "}Message")
            print batchErrorList[i].findtext("./{" + ns_adCenter + "}Details")

if __name__ == "__main__":
    import sys
    if len(sys.argv) == 4:
        createCampaigns(str(sys.argv[1]), str(sys.argv[2]), str(sys.argv[3]))
    else:
        # This application assumes the source file name is MyCreateCampaigns.py.
        # Update as needed if you use a different file name.
        print "Correct usage: python MyCreateCampaigns.py username password developerToken"