Yandex Metrika API use case.


If you use and monitor your web site statistics using Yandex Metrika, you can easily utilize Yandex Metrika API and Python to download all necessary data and use it later in external tools. You can conver downloaded data to .XLS or .CSV if necessary or just visualize output dataframe. You can also make use of Matplotlib and/or Seaborn to make additional graphs, but visualisation tasks are outside of the Yandex Metrika data extraction task.

Yandex Metrika API bot with Python.


The Yandex Metrika API is well documented on it's web page, to make the Python script below work all you have to do :

- Create an application to use Yandex Metrika API.
- Choose the name you want and select web-services type.
- Select section to use Yandex Metrika statistics.
- Get user ID and password and generate token.
- Run the script below, set ACCESS_TOKEN and METRIC_ID of your website.
- Uncomment line to export results to Excel if necessary.



Yandex Metrika API bot Python code:



from tapi_yandex_metrika import YandexMetrikaStats
import json
import pandas as pd

# use your access token
ACCESS_TOKEN = "AQAAAAAn5gQWAAhDiTiBm092p00djLuN-xEgk-a"
# use your metric ID
METRIC_IDS = "88167562"

# set limit or get 10000 rows by default

api = YandexMetrikaStats(
    access_token=ACCESS_TOKEN, 
    # if True, all data will be loaded, False by default
    receive_all_data=True
)
#parameters for tapi_yandex_metrika
params = dict(
    ids = METRIC_IDS,
    metrics = "ym:s:users,ym:s:visits,ym:s:pageviews,ym:s:bounceRate,ym:s:pageDepth,ym:s:avgVisitDurationSeconds",
    dimensions = "ym:s:date,ym:s:TrafficSource,ym:s:SourceEngine,ym:s:gender",
    date1 = "2daysAgo",
    date2 = "yesterday",
    sort = "ym:s:date",
    accuracy="full",
    limit = 300
)
#getting data Yandex.Metrika API
result = api.stats().get(params=params)
result = result().data
result = result[0]['data']

dict_data = {}
#parsing Json into dictionary
for i in range(0, len(result)-1):
    dict_data[i] = {
            'date':result[i]["dimensions"][0]["name"],
            'traffic-source':result[i]["dimensions"][1]["name"],
            'traffic-details':result[i]["dimensions"][2]["name"],
            'users':result[i]["metrics"][0],
            'visits':result[i]["metrics"][1],
            'pageviews':result[i]["metrics"][2],
            'bounceRate':result[i]["metrics"][3],
            'pageDepth':result[i]["metrics"][4],
            'avgVisitDurationSeconds':result[i]["metrics"][5]
          }
#creating DataFrame from dictionary
dict_keys = dict_data[0].keys()
df = pd.DataFrame.from_dict(dict_data, orient='index',columns=dict_keys)
#export to Excel
# df.to_excel("Report.xlsx", sheet_name='data', index=False)
df
Yandex Metrika output.




See also related topics: