Creating ads

Python version 2 or 3 using SOAP with the Suds library

This example shows a request using the Ads.add method, along with the result processing and output. To use the example, change the input data to specify the OAuth token and the ID of the group to create the new ad in. For a request on behalf of an agency, also specify the client login.

# -*- coding: utf-8 -*-
from suds.client import Client, WebFault
from suds.transport.http import HttpTransport

# Method for correctly parsing UTF-8 encoded strings for both Python 3 and Python 2
import sys

if sys.version_info < (3,):
    def u(x):
            return x.encode("utf8")
        except UnicodeDecodeError:
            return x
 def u(x):
 if type(x) == type (b''):
 return x.decode('utf8')
 return x

# Debugging information
# import logging
# logging.basicConfig(level=logging.INFO)
# logging.getLogger('suds.client').setLevel(logging.DEBUG)
# logging.getLogger('suds.transport').setLevel(logging.DEBUG)
# logging.getLogger('suds.xsd.schema').setLevel(logging.DEBUG)
# logging.getLogger('suds.wsdl').setLevel(logging. DEBUG)

# Additional class for correctly processing HTTP response headers for a SOAP request
class MyTransport(HttpTransport):
    def __init__(self, *args, **kwargs):
        HttpTransport.__init__(self, *args, **kwargs)
        self.last_headers = None

    def send(self, request):
        result = HttpTransport.send(self, request)
        self.last_headers = result.headers
        return result

# --- Input data ---
# Address of the WSDL description for the Campaigns service (case-sensitive)
AdsURL = ''

# OAuth token of the user that requests will be made on behalf of
token = 'TOKEN'

# Login of the advertising agency client
# Required parameter if requests are made on behalf of an advertising agency
clientLogin = 'CLIENT_LOGIN'

# ID of the ad group that the new ad will be created in
adGroupId = GROUP_ID

# --- Preparing, executing, and processing the request ---
# Creating HTTP request headers
headers = {
    "Authorization": "Bearer" + token, # OAuth token. The word Bearer must be used
    "Client-Login": clientLogin, # Login of the advertising agency client
    "Accept-Language": "ru", # Language for response messages

# SOAP client constructor
client = Client(AdsURL, location='')
client.set_options(transport=MyTransport())     # Setting an additional class for sending requests
client.set_options(headers=headers)             # Setting HTTP request headers

# Creating the request message body
params = {
 "Ads": [{
 "AdGroupId": adGroupId,
        "TextAd": { # Ad parameters
            "Title": u"Ad title",
             "Text": u"Ad Text",
             "Mobile": "NO",
             "Href": ""

# Executing the request
 result = client.service.add(**params)
 # Outputting the result
    print("RequestId: {}".format(client.options.transport.last_headers.get("requestid", False)))
    print("Information about points: {}".format(client.options.transport.last_headers.get("units", False)))
    #  Processing all elements in the AddResults array, where each element corresponds to a single ad
    for add in result:
        add = dict(add)
        # Processing nested elements (these may be Errors or Id, or possibly Warnings)
        if add.get ("Errors", False):
 # If the Errors array is present, the ad wasn't created due to an error (there may be multiple errors)
 for error in add["Errors"]:
 print("Error: {} - {} ({})".format(error ["Code"], u(error ["Message"]),
            # If the Id parameter is present, the ad was created
            print("Created ad №{}".format(add ["Id"]))
            # If the Warnings array is present, the ad was created, but with a warning (there may be multiple warnings)
            if add.get ("Warnings", False):
                for warning in add["Warnings"]:
                    print("Warning: {} - {} ({})".format(warning ["Code"], u(warning ["Message"]),
                                                         u(warning ["Details"])))

except WebFault as err:
    print("Error when accessing the Yandex Direct API server.")
    print("Error code: {}".format(err.fault['detail']['FaultResponse']['errorCode']))
    print("Error description: {}".format(u(err.fault['detail']['FaultResponse']['errorDetail'])))
    print("RequestId: {}".format(err.fault['detail']['FaultResponse']['requestId']))

    err = sys.exc_info()
    print('Error accessing the Yandex Direct API server: '+ str(err[1]))