Get campaigns

Python version 2 or 3 using JSON with the Requests 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 -*-
import requests, json
from requests.exceptions import ConnectionError
from time import sleep

#  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

# --- Input data ---
#  Address of the Campaigns service for sending JSON requests (case-sensitive)
CampaignsURL = 'https://api.direct.yandex.com/json/v5/campaigns'

# 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",  # Language for response messages
           }

# Creating the request body
body = {"method": "get",  # Method to use.
        "params": {"SelectionCriteria": {},  # Criteria for filtering campaigns. To get all campaigns, leave it emtpy
        "FieldNames": ["Id", "Name"]        # Names of parameters to get.
                   }}

# Encoding the request body as JSON
jsonBody = json.dumps(body, ensure_ascii=False).encode('utf8')

# Executing the request
try:
    result = requests.post(CampaignsURL, jsonBody, headers=headers)

    # Debugging information
    # print("Request headers: {}".format(result.request.headers))
    # print("Request: {}".format(u(result.request.body)))
    # print("Response headers: {}".format(result.headers))
    # print("Response: {}".format(u(result.text)))
    # print("\n")

    # Request handling
    if result.status_code != 200 or result.json().get("error", False):
        print("Error connecting to the Yandex.Direct API server.")
        print("Error code: {}".format(result.json()["error"]["error_code"]))
        print("Error description: {}".format(u(result.json()["error"]["error_detail"])))
        print("RequestId: {}".format(result.headers.get("RequestId", False)))
    else:
        print("RequestId: {}".format(result.headers.get("RequestId", False)))
        print("Information about points: {}".format(result.headers.get("Units", False)))
        # Output the campaign list
        for campaign in result.json()["result"]["Campaigns"]:
            print("Advertising campaign: {} №{}".format(u(campaign['Name']), campaign['Id']))

        if result.json()['result'].get('LimitedBy', False):
            # If the response contains the LimitedBy parameter, it means not all available objects were output.
            # In this case, send additional requests to get all objects.
            # Details on paginated selections  - https://tech.yandex.ru/direct/doc/dg/best-practice/get-docpage/#page
                    print("Not all objects received.")


# Error handling if the connection with the Yandex.Direct API server wasn't established.
except ConnectionError:
    # В In this case, we recommend repeating the request again later
    print("Error connecting to the API server.")

# If any other error occurred
    except:
        # In this case, we recommend analyzing the application's actions
        print("Unexpected error occurred.")