Creating ads

Python version 2 or 3 using JSON with the Requests library

This example shows a request using the {#T}.{#T} method, along with the result processing and output. To use this example, make sure that the input data specifies the OAuth token and the ID of the group where you want to create the new ad. If you're submitting a request on behalf of an agency, be sure to include the client's login.

# -*- coding: utf-8 -*-
import requests, json

# Method for properly parsing the UTF-8 encoded strings both in 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 Ads service for sending JSON requests (case-sensitive)
CampaignsURL = "https://api.direct.yandex.com/json/v5/ads"
OAuth token of the user who sends the requests
token = "TOKEN"

# The login of the advertising agency's client
# This parameter is required when submitting requests on behalf of an advertising agency
clientLogin = "CLIENT_LOGIN"

# ID of the ad group where you want to create a new ad
adGroupId = GROUP_ID

# --- Request preparation, execution, and processing ---
# Creating HTTP headers for the request
headers = {
    "Authorization": "Bearer " + token,  # Oauth token. The word “Bearer” is mandatory
    "Client-Login": clientLogin,  # Login of the advertising agency's client
    "Accept-Language": "ru",  # Language of response messages.
}

# Creating the request body
body = {
    "method": "add",                                    # Used method
    "params": {
        "Ads": [{
            "AdGroupId": adGroupId,
            "TextAd": {                                 # Ad parameters
                "Title": u"Ad title",
                "Text": u"Ad text",
                "Mobile": "NO",
                "Href": "http://www.yandex.com"
            }
        }
        ]
    }
}

# Encoding the request message 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")

    # Processing the request
    if result.status_code != 200 or result.json().get("error", False):
        print("Error sending a request 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:
        # Result output
        print("RequestId: {}".format(result.headers.get("RequestId", False)))
        print("Information about points: {}".format(result.headers.get("Units", False)))
        # Processing all items in the AddResults array, where each item corresponds to a single ad
        for add in result.json()["result"]["AddResults"]:
            # 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 one or more errors
                for error in add["Errors"]:
                    print("Error: {} - {} ({})".format(error["Code"], u(error["Message"]),
                                                 u(error["Details"])))
            else:
                # If the Id parameter is present, it indicates that the ad was created
                print("Created ad #{}".format(add["Id"]))
                # If the Warnings array is present, the ad was created, but with a warning (one or more)
                if add.get("Warnings", False):
                    for warning in add["Warnings"]:
                        print("Предупреждение: {} - {} ({})".format(warning["Code"], u(warning["Message"]),
                                                         u(warning["Details"])))

# Handling errors when unable to connect to the Yandex Direct API server
except ConnectionError:
    # In this case, we recommend repeating the request 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.")