Creating 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 executed on behalf of
token = "TOKEN"

# Login of the advertising agency client
# Required if requests are sent for an advertising agency
clientLogin = "CLIENT_NAME"

# 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 message 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 message body as JSON
jsonBody = json.dumps(body, ensure_ascii=False).encode('utf8')

# Executing the request
    result =, 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 accessing 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 results
        print("RequestId: {}".format(result.headers.get("RequestId", False)))
        print("Information about points: {}".format(result.headers.get("Units", False)))
        # Processing all elements in the AddResults array, where each element 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 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("ad #{} Created".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"])))

# 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
        # In this case, we recommend analyzing the application's actions
        print("Unexpected error occurred")