Working with the Yandex Metrica API: traffic breakdown by sources and UTM tags, conversion and search engine reports, API segments and direct access to counters.
Config
Required YANDEX_METRIKA_TOKEN в config/.env. For reading, access is needed
metrika:read, for creating segments and managing access — metrika:write.
Instruction: config/README.md.
Philosophy
- Cache-first — configuration data (counters, goals, info) is cached for a long time. Reports are cached by the key counter+dates+params. Before an API request, always check the cache.
- Context window hygiene — stdout is limited to 30 lines. Full data in CSV/file. The cache is available via grep/rg for searching without loading into context.
- Exact data — accuracy=1 (no sampling), isRobot filter by default.
- Attribution — default
lastsign(last significant source). We ask the user on first run.
Workflow
STOP! Before any analysis:
-
Get the list of counters:
bash scripts/counters.sh -
Ask the user (if the counter is not obvious from the context):
"О каком счётчике/сайте идёт речь? Укажите ID, название или домен."If the user named a site/domain — search via
--search:bash scripts/counters.sh --search "metallik"This is a grep over TSV (id + name + site), so it also finds by domain.
-
Get info about the counter and its goals:
bash scripts/counter_info.sh --counter <ID> bash scripts/goals.sh --counter <ID> -
Ask about conversion goals:
"Какие из этих целей являются конверсионными для вашего бизнеса? [список целей из goals.sh] Сохраню выбранные для будущих отчётов." -
Save the configuration в
cache/counter_<id>/config.json:{ "attribution": "lastsign", "conversion_goals": [ {"id": 12345, "name": "Заказ оформлен"}, {"id": 67890, "name": "Заявка отправлена"} ] } -
Run reports according to the user's task.
Segments and access
For an API segment, first fix a clear name and expression filters.
Creation and deletion without --apply show a plan and change nothing.
Before writing, the script reads the fresh role on the counter; the API server remains
the final source of rights.
bash scripts/segments.sh --counter <ID> --action create \
--name "Посетители карточек" \
--expression "EXISTS(ym:pv:URL=@'/catalog/')"
# после проверки плана повторить с --apply
Get the exact login from the calling task, then check direct access to the counter and, if necessary, prepare a minimal role:
bash scripts/grants.sh --counter <ID> --action get --login <LOGIN>
bash scripts/grants.sh --counter <ID> --action add \
--login <LOGIN> --permission view
# после проверки плана повторить с --apply
To use a segment, viewis usually sufficient. Do not grant edit, if
the task does not require changing the counter. If the user selected analyst or edit,
pass this role via --permission; change an existing role via update.
The list /grants contains direct permissions;
the owner is returned separately, and account representatives are not included in this list.
After writing, return to the calling task the counter number, segment ID, login, and
the confirmed role.
Details: API segments и
direct counter accesses.
Scripts
Common call pattern:
bash scripts/<script>.sh --counter <ID> --date1 YYYY-MM-DD [--date2 ...] [--group month] [--csv path]
| Script | Description | Special params |
|---|---|---|
counters.sh |
List of counters | --search "query" |
goals.sh |
Counter goals | — |
counter_info.sh |
Counter metadata | — |
traffic_summary.sh |
Traffic by source | — |
conversions.sh |
Goal achievement | --goals "ID,ID" / --all-goals; by default from config.json |
utm_report.sh |
UTM breakdown | — |
search_engines.sh |
Search engines (organic) | — |
ecommerce.sh |
Purchases, revenue, average order value | --currency RUB|USD|EUR; auto from counter_info |
direct_clients.sh |
Direct logins | — |
direct_costs.sh |
Direct expenses (ym:ad:*) |
--direct-client-logins "login"; no --group/--device/--source |
comparison.sh |
Comparison of two periods | --date1a/--date2a/--date1b/--date2b; --dimension, --metrics |
segments.sh |
List, view, create, and delete API segments | --action; write only with --apply |
grants.sh |
Owner and direct accesses by logins; roles view, analyst, edit |
--action; write only with --apply |
Not all scripts support all common parameters — see Special params.
Management scenarios segments.sh и grants.sh require Python 3.10+ or uvfor reliable JSON parsing;
regular reports still work without them.
Goal report
conversions.sh automatically requests goals in batches of six and merges them
into a single CSV. This works for --all-goals, --goals and goals from config.json.
With --all-goals , the list of goals is first updated via the Management API.
Merging is performed by a regular awk; Python and uv are not needed to run reports.
Three metrics are saved for each goal: visits with achievement, achievements, and conversion.
The order of goals in the columns corresponds to the selected list.
A total visits metric is added to the requests so that sources with zero conversions do not disappear from individual parts. The final CSV has no service metrics, but sources without conversions are preserved; the final conversion rate takes their visits into account. Sources are sorted by visits with an achievement of the first selected goal, and in case of a tie — by source.
--limit limits the number of sources: without --group 1–100000 is allowed
(default 100); with --group — 1–30 (default 30, API parameter top_keys).
Dates are not shortened in this case. The report is cached and --csv only after
all parts have been successfully retrieved and merged.
Common parameters of reporting scripts
| Param | Required | Default | Values |
|---|---|---|---|
--counter |
yes | - | counter ID |
--date1 |
yes | - | YYYY-MM-DD |
--date2 |
no | today | YYYY-MM-DD |
--group |
no | - | day, week, month |
--device |
no | all | desktop, mobile, tablet |
--source |
no | all | organic, ad, referral, direct, social |
--attribution |
no | lastsign | lastsign, last, first |
--filters |
no | without robots | Reports API segmentation expression |
--limit |
no | API default | number of rows |
--csv |
no | - | export path |
--no-cache |
no | - | skip cache |
Cache strategy
The cache is stored in cache/:
counters.json+counters.tsv— all counterscounter_<id>/info.json— metadata (permanent)counter_<id>/goals.json+goals.tsv— goalscounter_<id>/config.json— attribution, conversion goalscounter_<id>/direct_clients.json— Direct loginscounter_<id>/reports/*.csv— report results
Segments and accesses are always read anew and are not saved to the cache: this data changes independently of reports, and the access list contains user logins.
To search the cache: grep "text" cache/counters.tsv or rg "text" cache/.
Advanced scenarios
- Popular search queries
- Custom reports and JSON requests (drilldown, metrika_get, etc.)
- Dimensions/metrics reference
- Year-over-year period comparison
- Direct costs and PnL
- API segments for audience targeting in Direct
- Checking and granting access to advertising accounts
- API limitations (bytime, scope mixing, drilldown CSV)
API limits
- Reporting API: ~200 requests / 5 minutes (if exceeded — wait ~5 minutes)
- The scripts automatically handle 429 (Retry-After ≤ 60s → retry, otherwise fail with a message)