tapi-yandex-metrika Python Client

repository·master·Indexed 41 days ago

https://github.com/pavelmaksimov/tapi-yandex-metrika

A Python client for interfacing with Yandex Metrika API endpoints, including Management, Stats, and Logs APIs. It provides specialized clients like YandexMetrikaLogsapi for report lifecycle management and data transformation, YandexMetrikaManagement for configuration and resource handling, and YandexMetrikaStats for retrieving statistical data with support for pagination and row iteration.

Tokens
4.1K
Snippets
16
Records
18
Agent score
50%

What's inside tapi-yandex-metrika

  1. Explore available Management API resources

    master

    The YandexMetrikaManagement client provides access to various Yandex Metrika resources. You can discover available resource methods by calling dir(client). Common resources include:

    • counters / counter
    • goals / goal
    • accounts
    • delegates / delegate
    • segments / segment
    • labels / label
    • ...and many others related to offline conversions, user params, and yclid conversions.

    To interact with a specific resource, you call the resource method on the client (e.g., client.counters()).

    # List all available resource methods on the client
    print(dir(client))
  2. Download and process LOGS API reports

    master

    Once a report status is processed, you can download it. Reports may consist of multiple parts.

    Manual Download

    Use client.download(requestId=request_id, partNumber=N).get() where partNumber is the index of the part (default is 0).

    Automatic Download (Wait for report)

    To avoid manual polling, initialize the client with wait_report=True. The client.create().post() call will block until the report is ready, allowing you to call client.download(requestId=request_id).get() immediately.

    Data Transformation

    Downloaded report parts can be transformed into different formats using the following methods:

    • to_values(): Returns data as values.
    • to_lines(): Returns data as lines.
    • to_dicts(): Returns data as dictionaries.
    • to_columns(): Returns data in columns data orient.
    from tapi_yandex_metrika import YandexMetrikaLogsapi
    
    # Using wait_report=True to automate the process
    client = YandexMetrikaLogsapi(
        access_token=ACCESS_TOKEN, 
        default_url_params={'counterId': COUNTER_ID}, 
        wait_report=True
    )
    
    params = {"fields": "ym:s:date,ym:s:clientID", "source": "visits", "date1": "2019-01-01", "date2": "2019-01-01"}
    info = client.create().post(params=params)
    request_id = info["log_request"]["request_id"]
    
    # This will return the report once it is ready
    report = client.download(requestId=request_id).get()
    
    print(report.columns)
    print(report().to_dicts())
  3. Download reports using YandexMetrikaStats

    master

    To download reports from Yandex Metrika, initialize YandexMetrikaStats with your access_token and use the .stats().get(params=...) method. The params dictionary should follow the Yandex Metrika API specification. Common keys include:

    • ids: The Counter ID.
    • date1: Start date (string or date object).
    • date2: End date (string or date object).
    • metrics: Metric identifiers (e.g., ym:s:visits).
    • dimensions: Dimension identifiers (e.g., ym:s:date).
    • sort: Sorting criteria.
    • lang: Language code.
    import datetime as dt
    from tapi_yandex_metrika import YandexMetrikaStats
    
    ACCESS_TOKEN = ""
    COUNTER_ID = ""
    
    client = YandexMetrikaStats(access_token=ACCESS_TOKEN)
    
    params = dict(
        ids=COUNTER_ID,
        date1="2020-10-01",
        date2=dt.date(2020,10,5),
        metrics="ym:s:visits",
        dimensions="ym:s:date",
        sort="ym:s:date",
        lang="en",
    )
    report = client.stats().get(params=params)
  4. Initialize the YandexMetrikaManagement client

    master

    To use the Counter Management API, import YandexMetrikaManagement from tapi_yandex_metrika. You must provide an access_token and can optionally provide default_url_params (such as counterId) to be included in all subsequent requests.

    from tapi_yandex_metrika import YandexMetrikaManagement
    
    ACCESS_TOKEN = ""
    COUNTER_ID = ""
    
    client = YandexMetrikaManagement(
        access_token=ACCESS_TOKEN,
        default_url_params={'counterId': COUNTER_ID}
    )
  5. Install tapi-yandex-metrika via pip

    master

    You can install the client using pip. Note that the latest version contains backward incompatible changes compared to older versions.

    To install the latest version:

    pip install --upgrade tapi-yandex-metrika==2022.4.8

    To install a specific older version:

    pip install --upgrade tapi-yandex-metrika==2020.10.20
  6. Manage Yandex Metrika LOGS API reports

    master

    The YandexMetrikaLogsapi client provides methods to manage the lifecycle of reports via the Yandex Metrika LOGS API. Note that different resources require specific HTTP methods:

    • Check report possibility: Use client.evaluate().get(params=params) to verify if a report can be created with specific parameters.
    • Order a report: Use client.create().post(params=params) to start report generation. This returns a request_id.
    • Cancel a report: Use client.cancel(requestId=request_id).post().
    • Delete a report: Use client.clean(requestId=request_id).post().
    • List all reports: Use client.allinfo().get() to see reports stored on the server.
    • Get report status: Use client.info(requestId=request_id).get() to check if a report is processed.
    from tapi_yandex_metrika import YandexMetrikaLogsapi
    
    client = YandexMetrikaLogsapi(access_token=ACCESS_TOKEN, default_url_params={'counterId': COUNTER_ID})
    params = {"fields": "ym:s:date,ym:s:clientID", "source": "visits", "date1": "2021-01-01", "date2": "2021-01-01"}
    
    # Check possibility
    result = client.evaluate().get(params=params)
    
    # Order report
    result = client.create().post(params=params)
    request_id = result["log_request"]["request_id"]
    
    # Cancel
    client.cancel(requestId=request_id).post()
    
    # Delete
    client.clean(requestId=request_id).post()
  7. Iterate through report pages

    master

    If a report is large and split into multiple pages, you can iterate through them using report().pages(). Each page object provides its own data and formatting methods:

    • report().pages(): Returns an iterator of page objects.
    • page().data: Raw data for that specific page.
    • page().values(): Iterator of rows as values for that page.
    • page().dicts(): Iterator of rows as dictionaries for that page.
    • page().to_values(), page().to_dicts(), page().to_columns(): Formatted data for the entire page.
    for page in report().pages():
        print(page.data)
        for row_as_values_of_page in page().values():
            print(row_as_values_of_page)
        for row_as_dict_of_page in page().dicts():
            print(row_as_dict_of_page)
  8. Access specific resource instances by ID

    master

    For many resources, you need to target a specific object (e.g., a single goal) rather than the collection. This is achieved by passing the identifier as an argument to the resource method itself (e.g., client.goal(goalId=123)).

    # Get information about a specific goal
    client.goal(goalId=10000).get()
    
    # Update a specific goal
    client.goal(goalId=10000).put(data=body)
    
    # Delete a specific goal
    client.goal(goalId=10000).delete()
  9. Inspect API response data and metadata

    master

    Every request returns an object containing the parsed data and the raw response information. Use these attributes to inspect the results:

    • result.data: The parsed response body (e.g., the list of counters or goal details).
    • result.response: The raw response object.
    • result.response.headers: The HTTP response headers.
    • result.status_code: The HTTP status code returned by the server.
    response = client.counters().get()
    print(response.data)           # The actual data returned
    print(response.status_code)    # e.g., 200
    print(response.response.headers) # HTTP headers
  10. Extract data from a report object

    master

    A report object returned by .get() provides access to raw data and several methods to format the data for different use cases:

    • report.data: Access the raw data.
    • report.columns: Access the column names.
    • report.response: Access the underlying HTTP response object (includes status_code and headers).
    • report().to_values(): Returns data as a list of lists (rows).
    • report().to_dicts(): Returns data as a list of dictionaries.
    • report().to_columns(): Returns data in a column-oriented format (list of lists where each sub-list is a column).
    # Example of data extraction
    print(report.data)
    print(report.columns)
    
    # Formatted outputs
    print(report().to_values())
    print(report().to_dicts())
    print(report().to_columns())
  11. Get help and documentation for Management resources

    master

    If you need to know the available query parameters or the specific structure required for a resource, you can use the built-in help methods:

    • resource.help(): Prints help information about the method (including available query parameters and resource paths).
    • resource.open_docs(): Opens the official Yandex Metrika documentation for that resource in your default web browser.
    # Get help text for the counters resource
    client.counters().help()
    
    # Open the official documentation in a browser
    client.counters().open_docs()