Export (0) Print
Expand All

Submit an Ad Group for Approval in Python

The following example shows how to submit an ad group for editorial approval using the Campaign Management SubmitAdGroupForApproval service operation.

This example has been developed and run within the environment described in Getting Started Using Python with Bing Ads Services.

System_CLiX_note Note

This example uses the UserName and Password elements for authentication. For Managing User Authentication with OAuth, replace the UserName and Password elements with the AuthenticationToken, which is your OAuth access token.


# This application expects the user name, password, and
# developer token to be passed in as command-line arguments.
# Command line usage: python MySubmitAdGroupForApproval.py username password developerToken
# 

import elementtree.ElementTree as ET
import httplib

# Application-specific values.
acctId = <accountidgoeshere>
adGroupId = <adgroupidgoeshere>

# This example host is for the sandbox environment.
# Update the URL as needed when you use the production environment.
host = "api.sandbox.bingads.microsoft.com"
# The following is the production host.
# host = "adcenterapi.microsoft.com"

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

# The namespace definitions.
ns_soapenv = "http://schemas.xmlsoap.org/soap/envelope/"
ns_xsd = "http://www.w3.org/1999/XMLSchema"
ns_xsi = "http://www.w3.org/2001/XMLSchema-instance"
ns_soapenc = "http://schemas.xmlsoap.org/soap/encoding/"
ns_arrays = "http://schemas.microsoft.com/2003/10/Serialization/Arrays"
ns_bingads = "https://adcenter.microsoft.com/v8"
ns_adAPI = "https://adapi.microsoft.com"

# 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 that contains
# the SubmitAdGroupForApproval request.
def createSoapRequest(username, password, devtoken):
    
    # Create the root element.
    root = ET.Element("{" + ns_soapenv + "}Envelope")

    # Create the header element.
    header = ET.SubElement(root,"{" + ns_soapenv + "}Header")
    header.attrib["xmlns"] = ns_bingads

    # Add in the developer token.
    devToken = ET.SubElement(header,"DeveloperToken")
    devToken.text = devtoken
    
    # Add in the user name.
    userName = ET.SubElement(header,"UserName")
    userName.text = username
    
    # Add in the password.
    passWord = ET.SubElement(header,"Password")
    passWord.text = password

    # Add in the customer account ID.
    accountId = ET.SubElement(header,"CustomerAccountId")
    accountId.text = str(acctId)
    
    # Create the body element.
    body = ET.SubElement(root,"{" + ns_soapenv + "}Body")
    body.attrib["xmlns"] = ns_bingads
    
    # Create the SubmitAdGroupForApprovalRequest element.
    submitAdGroupForApprovalRequest = \
        ET.SubElement(body,"SubmitAdGroupForApprovalRequest")
    
    # Add in the account ID to the request.
    accountIdRequest = ET.SubElement(submitAdGroupForApprovalRequest,"AccountId")
    accountIdRequest.text = str(acctId)

    # Add in the ad group ID to the request.
    adGrpId = ET.SubElement(submitAdGroupForApprovalRequest,"AdGroupId")
    adGrpId.text = str(adGroupId)

    return root

# Create a Web service client, and then execute the AddAdGroups method.
def createAdGroups(username,password,devtoken): 

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

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

    # Execute the Web service request.
    _service.send(soapStr)
    
    # Get the response message and results.
    statuscode, statusmessage, header = _service.getreply()
    res = _service.getfile().read()
    
    if statusmessage == "OK":
    
        # The method call was successful.
        print action + " succeeded."
        
        # Display the tracking ID.
        responseTree = ET.fromstring(res)
        print "Tracking ID: " + responseTree.findtext(".//{" + ns_bingads + "}TrackingId")
        
    else:

        # The method call failed.
        print soapStr
        print action + " failed.\n"
        print "Status Code: ", statuscode, statusmessage, "\n"
        print "Header: ", header, "\n"
        print res
        
        faultTree = ET.fromstring(res)
        print faultTree.findtext(".//faultcode"), " ", \
            faultTree.findtext(".//faultstring")

        # The error received could be either ApiFaultDetail or AdApiFaultDetail.
        if None != faultTree.find(".//{" + ns_adAPI + "}AdApiFaultDetail"):
            #
            print "AdApiFaultDetail exception encountered."
            print "Tracking ID: " + faultTree.findtext(".//{" + ns_adAPI + "}TrackingId")
            # Display AdApiErrors.
            errorList = faultTree.findall(".//{" + ns_adAPI + "}AdApiError")
            for error in errorList:
                message = error.find("{" + ns_adAPI + "}Message")
                detail = error.find("{" + ns_adAPI + "}Detail")
                errorCode = error.find("{" + ns_adAPI + "}ErrorCode")
                code = error.find("{" + ns_adAPI + "}Code")
                print "Error encountered:"
                print "\tMessage   : ", message.text
                print "\tDetail    : ", detail.text
                print "\tErrorCode : ", errorCode.text
                print "\tCode      : ", code.text

        else:
            if None != faultTree.find(".//{" + ns_bingads + "}ApiFaultDetail"):
                print "ApiFaultDetail exception encountered."
                print "Tracking ID: " + \
                    faultTree.findtext(".//{" + ns_adAPI + "}TrackingId")

                # Display operation errors.
                operationErrorList = faultTree.findall(".//{" + ns_bingads + "}OperationError")
                for operationError in operationErrorList:
                    message = operationError.find("{" + ns_bingads + "}Message")
                    details = operationError.find("{" + ns_bingads + "}Details")
                    errorCode = operationError.find("{" + ns_bingads + "}ErrorCode")
                    code = operationError.find("{" + ns_bingads + "}Code")
                    print "Operation error encountered:"
                    print "\tMessage   : ", message.text
                    print "\tDetails   : ", details.text
                    print "\tErrorCode : ", errorCode.text
                    print "\tCode      : ", code.text
                    print # Blank line.

                # Display batch errors.
                batchErrorList = faultTree.findall(".//{" + ns_bingads + "}BatchError")
                for batchError in batchErrorList:
                    index = batchError.find("{" + ns_bingads + "}Index")
                    message = batchError.find("{" + ns_bingads + "}Message")
                    details = batchError.find("{" + ns_bingads + "}Details")
                    errorCode = batchError.find("{" + ns_bingads + "}ErrorCode")
                    code = batchError.find("{" + ns_bingads + "}Code")
                    print "Batch error encountered for array index " +  \
                           index.text + "."
                    print "\tMessage   : ", message.text
                    print "\tDetails   : ", details.text
                    print "\tErrorCode : ", errorCode.text
                    print "\tCode      : ", code.text
                    print # Blank line.

        print # Blank line.
        print "Response: ", res
 
if __name__ == "__main__":
    import sys
    
    if len(sys.argv) == 4:

        # Use the command-line parameters to create the request that
        # is used to call the Web service.
        # args[1] is the user name.
        # args[2] is the password.
        # args[3] is the developer token.
        createAdGroups(sys.argv[1], sys.argv[2], sys.argv[3])

    else:

        # This application expects the user name, password, and
        # developer token to be passed in as command-line arguments.
        print "Correct usage: python MySubmitAdGroupForApproval.py " + \
            " username password developerToken"


Community Additions

Show:
© 2014 Microsoft