# GET /v1/stats

Obtener estadísticas

Pops, ingresos y eCPM del editor, agrupados por date, hour, site, zone, country, device, os, browser o page_domain; JSON o CSV. El filtro de navegador acepta claves canónicas de navegador. Los ingresos por navegador se asignan en proporción a las impresiones. La vista por navegador puede no estar disponible o estar desactivada; consulta /v1/stats/availability. Si la agrupación o el filtro por navegador no están disponibles, se devuelve 400 breakdown_unavailable con breakdown browser (JSON y CSV) antes de ejecutar las consultas de estadísticas. Agrupar o filtrar por page_domain solo es posible cuando la medición está activa: antes devuelve 400 `page_domain_unavailable`, y las respuestas JSON incluyen `page_domain_available`. Si group_by contiene `hour`, el rango (ambos extremos incluidos, días hábiles EST) debe ser de 31 días como máximo; de lo contrario, 400 `hour_range`; los ingresos por hora de los días finalizados son una asignación de los ingresos diarios (la respuesta incluye `hourly_revenue_allocated: true`), no una medición por hora; las horas de los días aún no finalizados son estimaciones. Las horas en JSON son ISO UTC; las horas en CSV se muestran en EST (UTC-5). Cada fila tiene el estado estimated, reported, final o mixed; con cero impresiones válidas el eCPM es null. La respuesta identifica el recuento aceptado y la instantánea de importes. Requiere el scope publisher:read (clave de API o sesión web). Nivel de límite de uso: stats.

- Scope requerido: `publisher:read`
- Límite de uso: `stats` — 30 solicitudes por ventana de 60 s por clave de API o sesión web

## Parámetros

| Nombre | En | Tipo | Requerido |
|---|---|---|---|
| `from` | query | string | sí |
| `to` | query | string | sí |
| `group_by` | query | ("date" \| "hour" \| "site" \| "zone" \| "country" \| "device" \| "os" \| "browser" \| "page_domain")[] | no |
| `metrics` | query | ("pops" \| "revenue" \| "ecpm")[] | no |
| `site_id` | query | integer | no |
| `zone_id` | query | integer | no |
| `country` | query | string | no |
| `browser` | query | "chrome" \| "safari" \| "firefox" \| "edge" \| "samsung_internet" \| "opera" \| "uc_browser" \| "yandex" \| "other" | no |
| `page_domain` | query | string | no |
| `format` | query | "json" \| "csv" | no |

## Respuesta

```
{ browser_missing_days?: string[]; count_basis?: "valid" | "legacy" | "mixed"; currency: "USD"; data_as_of?: string | null; estimated_from: string | null; forecast_basis_version?: "forecast-basis-v1"; forecast_generation?: string; forecast_updated_at?: string | null; hourly_revenue_allocated?: true; measurement_definition?: { complete: boolean; includes_direct: boolean; includes_legacy: boolean; tag_valid_after_ms: integer[] }; measurement_generation?: string; measurement_status?: "ok" | "stale" | "updating"; measurement_updated_at?: string | null; money_basis_version?: string; money_generation?: string; page_domain_available?: boolean; rows: { browser?: "chrome" | "safari" | "firefox" | "edge" | "samsung_internet" | "opera" | "uc_browser" | "yandex" | "other"; country?: string; date?: string; device?: string; ecpm?: string | null; hour?: string; os?: string; page_domain?: string | null; pops?: integer; publisher_id?: integer; revenue?: string; site_deleted?: true; site_domain?: string; site_id?: integer; status?: "estimated" | "reported" | "final" | "mixed"; zone_deleted?: true; zone_id?: integer; zone_name?: string }[]; totals: { ecpm: string | null; pops: integer; revenue: string; status?: "estimated" | "reported" | "final" | "mixed" }; truncated?: boolean; updated_at?: string | null }
```

## Errores

Las rutas con límite de uso devuelven `RateLimit-Limit`, `RateLimit-Remaining` y `RateLimit-Reset` (segundos hasta que termina la ventana); un 429 incluye además `Retry-After`. Los encabezados pueden faltar mientras el limitador no esté disponible temporalmente (en ese caso las solicitudes se dejan pasar).

| Estado | Significado |
|---|---|
| 401 | Clave de API ausente, no válida o revocada. |
| 403 | La clave no tiene el scope requerido, o la operación no está permitida para este actor. |
| 429 | Límite de uso superado; espera los segundos indicados en `Retry-After`. |
| 400 | Default Response |
| 404 | Default Response |
| 503 | Default Response |

## Ejemplos

### cURL

```bash
#!/usr/bin/env bash
# GET /v1/stats: daily pops, revenue and eCPM for the last 7 calendar days (EST, fixed UTC-5).
# Needs: AGIMONE_API_KEY (create one at https://app.agimone.com/app/account/api-keys). Optional: AGIMONE_API_BASE, AGIMONE_FROM, AGIMONE_TO.
set -euo pipefail
BASE="${AGIMONE_API_BASE:-https://app.agimone.com}"
# Snapshot the EST day once; calendar arithmetic uses that date label.
TODAY="$(TZ=Etc/GMT+5 date +%F)"
# `date -v` is BSD/macOS, `date -d` is GNU/Linux.
FROM="${AGIMONE_FROM:-$(date -u -j -v-6d -f '%Y-%m-%d' "$TODAY" +%F 2>/dev/null || date -u -d "$TODAY -6 days" +%F)}"
TO="${AGIMONE_TO:-$TODAY}"
curl -fsS -H "Authorization: Bearer $AGIMONE_API_KEY" \
  "$BASE/v1/stats?from=$FROM&to=$TO&group_by=date&metrics=pops,revenue,ecpm"
echo
```

### Node.js

```js
// GET /v1/stats: daily pops, revenue and eCPM for the last 7 calendar days (EST, fixed UTC-5). Node 18+, no dependencies.
// Needs: AGIMONE_API_KEY (create one at https://app.agimone.com/app/account/api-keys). Optional: AGIMONE_API_BASE, AGIMONE_FROM, AGIMONE_TO.
const base = process.env.AGIMONE_API_BASE ?? 'https://app.agimone.com';
const parts = new Intl.DateTimeFormat('en-US', { timeZone: 'Etc/GMT+5', year: 'numeric', month: '2-digit', day: '2-digit' }).formatToParts(new Date());
const part = (type) => parts.find((p) => p.type === type).value;
const today = `${part('year')}-${part('month')}-${part('day')}`;
const day = (offset) => new Date(Date.parse(`${today}T00:00:00Z`) + offset * 86_400_000).toISOString().slice(0, 10);
const query = new URLSearchParams({
  from: process.env.AGIMONE_FROM ?? day(-6),
  to: process.env.AGIMONE_TO ?? today,
  group_by: 'date',
  metrics: 'pops,revenue,ecpm',
});

const res = await fetch(`${base}/v1/stats?${query}`, {
  headers: { Authorization: `Bearer ${process.env.AGIMONE_API_KEY}` },
});
if (!res.ok) {
  console.error(`HTTP ${res.status}: ${await res.text()}`);
  process.exit(1);
}
console.log(JSON.stringify(await res.json()));
```

### PHP

```php
<?php
// GET /v1/stats: daily pops, revenue and eCPM for the last 7 calendar days (EST, fixed UTC-5). PHP 8 with the curl extension, no other dependencies.
// Needs: AGIMONE_API_KEY (create one at https://app.agimone.com/app/account/api-keys). Optional: AGIMONE_API_BASE, AGIMONE_FROM, AGIMONE_TO.
$base = getenv('AGIMONE_API_BASE') ?: 'https://app.agimone.com';
$today = new DateTimeImmutable('now', new DateTimeZone('Etc/GMT+5'));
$query = http_build_query([
    'from' => getenv('AGIMONE_FROM') ?: $today->modify('-6 days')->format('Y-m-d'),
    'to' => getenv('AGIMONE_TO') ?: $today->format('Y-m-d'),
    'group_by' => 'date',
    'metrics' => 'pops,revenue,ecpm',
]);

$ch = curl_init("$base/v1/stats?$query");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('AGIMONE_API_KEY')],
    CURLOPT_TIMEOUT => 15,
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
if ($body === false || $status >= 400) {
    fwrite(STDERR, "HTTP $status: " . ($body === false ? curl_error($ch) : $body) . "\n");
    exit(1);
}
curl_close($ch);
echo trim($body), "\n";
```

### Python

```python
# GET /v1/stats: daily pops, revenue and eCPM for the last 7 calendar days (EST, fixed UTC-5). Python 3.8+, standard library only.
# Needs: AGIMONE_API_KEY (create one at https://app.agimone.com/app/account/api-keys). Optional: AGIMONE_API_BASE, AGIMONE_FROM, AGIMONE_TO.
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timedelta, timezone

base = os.environ.get("AGIMONE_API_BASE", "https://app.agimone.com")
# Fixed UTC-5 is Etc/GMT+5; Python 3.8 needs no zoneinfo/tzdata dependency.
today = datetime.now(timezone(timedelta(hours=-5))).date()
query = urllib.parse.urlencode({
    "from": os.environ.get("AGIMONE_FROM", str(today - timedelta(days=6))),
    "to": os.environ.get("AGIMONE_TO", str(today)),
    "group_by": "date",
    "metrics": "pops,revenue,ecpm",
})
req = urllib.request.Request(
    f"{base}/v1/stats?{query}",
    headers={"Authorization": f"Bearer {os.environ['AGIMONE_API_KEY']}"},
)
try:
    with urllib.request.urlopen(req, timeout=15) as res:
        print(json.dumps(json.load(res)))
except urllib.error.HTTPError as e:
    print(f"HTTP {e.code}: {e.read().decode()}", file=sys.stderr)
    sys.exit(1)
```

Documentación HTML: https://agimone.com/es/developers/api/#get-stats
API 2026-10
