Get campaigns

Python version 2 or 3 using SOAP with the Suds library

This example shows a request using the Campaigns.get method, along with the result processing and output. To use the example, specify the OAuth access token in the input data. 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):
        try:
            return x.encode("utf8")
        except UnicodeDecodeError:
            return x
else:
    def u(x):
        if type(x) == type(b''):
            return x.decode('utf8')
        else:
            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)
CampaignsURL = 'https://api.direct.yandex.com/v5/campaigns?wsdl'

# 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'

# --- 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",                    # Response language
}

# SOAP client constructor
client = Client(CampaignsURL, location='https://api.direct.yandex.com/v5/campaigns')
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 = {
    "SelectionCriteria": {},                    # Criteria for filtering campaigns. To get all campaigns, leave it empty
    "FieldNames": ["Id", "Name"]                # Names of parameters to get
}

# Executing the request
try:
    result = client.service.get(**params)
    print("RequestId: {}".format(client.options.transport.last_headers.get("requestid",False)))
    print("Информация о баллах: {}".format(client.options.transport.last_headers.get("units", False)))
    for campaign in result["Campaigns"]:
        print("Ad campaign: {} №{}".format(u(campaign['Name']), campaign['Id']))

except WebFault as err:
    print("Error connecting to 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']))

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