Create ads

Python version 2 or 3 using JSON with the Requests 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 -*-
import requests, json

# 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

# --- Input data ---
# Address of the Ads service for sending JSON requests (case-sensitive)
CampaignsURL = ""
OAuth token of the user that requests will be made on behalf of
token = "TOKEN"

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

# ID of the ad group to create the new ad 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": "en",  # Language for response messages

# Creating the request body
body = {
    "method": "add",                                    # Method to use
    "params": {
        "Ads": [{
            "AdGroupId": adGroupId,
            "TextAd": {                                 # Ad parameters
                "Title": u"Ad title",
                "Text": u"Ad text",
                "Mobile": "NO",
                "Href": ""

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

# Executing the request
    result =, jsonBody, headers=headers)

    # Debugging information
    # print("Request header: {}".format(result.request.headers))
    # print("Request: {}".format(u(result.request.body)))
    # print("Response header: {}".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)))
        # Outputting the result
        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 (either Errors, or Id, or possibly Warnings)
            if add.get("Errors", False):
                # If the Errors array is present, the ad isn't created due to an error (there may be several 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 is created with a warning (there may be several warnings)
                if add.get("Warnings", False):
                    for warning in add["Warnings"]:
                        print("Warning: {} - {} ({})".format(warning["Code"], u(warning["Message"]),

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

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