JSON

Examples of accessing the API using Python in JSON format.

Getting information about the client

This example demonstrates calling the GetClientInfo method.

import json, urllib2

#Address for sending JSON requests
url = 'https://api.direct.yandex.ru/v/json/'

#data for OAuth authorization
token = 'e4d3b4d2a7444fa384a18cda5cd1c8d9'

#Yandex Direct login
login = 'agrom'

#input data structure (dictionary)
data = {
   'method': 'GetClientInfo',
   'token': token,
   'locale': 'ru',
   'param': [login]
}

#convert the dictionary to JSON format and UTF-8 encoding
jdata = json.dumps(data, ensure_ascii=False).encode ('utf8')

#execute the request
response = urllib2.urlopen(url,jdata)

#output the result
print response.read().decode('utf8')

Calling finance methods

When calling the finance method, you must additionally specify the finance token and the transaction number (see Accessing finance methods).

As an example, we will call the CreateInvoice method, which creates an invoice. Below you can see how the finance token is formed. The input data are the master token (obtained from the Yandex Direct interface), the transaction number, the method name, and the username.

import hashlib

masterToken  = 'AEgchkX2M3FBL8lU'
operationNum = 119
usedMethod   = 'CreateInvoice'
login        = 'agrom'

financeToken = hashlib.sha256(masterToken + str(operationNum) + usedMethod + login).hexdigest()
print financeToken

This creates a single-use finance token for calling the CreateInvoice method for the user agrom. An example of the token is shown below.

7215f95e84a766971d8ec4eb5a39ae96505b3a5529a91e5a03e5943565a6e6c7

The finance token and transaction number are included in the input data structure, as shown below.

#input data structure (dictionary)
data = {
   'method': 'GetCreditLimits',
   'token': token,
   'finance_token': financeToken,
   'operation_num': operationNum,
   'param': ['agrom'],
   'locale': 'ru'
}