# Statistik harian

Hitungan per hari dalam rentang from sampai to: pesan keluar per status akhir, pesan masuk, dan Quota terpakai (satu pesan keluar satu Quota).

Statistik harian: parameter, body request, response per kode status, dan error untuk GET /v1/stats.

## Request

**GET** `https://api.gocap.id/v1/stats`

Autentikasi: API key akun di header `Authorization: Bearer`.

Hitungan per hari dalam rentang `from` sampai `to`: pesan keluar per status akhir, pesan masuk, dan Quota terpakai (satu pesan keluar satu Quota). Hari mengikuti WIB (Asia/Jakarta, UTC+7): `from`, `to`, dan `day` adalah tanggal WIB, bukan UTC. Tanpa `from` dan `to`: 30 hari terakhir sampai hari ini; hanya `to`: 30 hari sampai `to`; hanya `from`: sampai hari ini. Rentang paling panjang 366 hari; tanggal yang bukan YYYY-MM-DD, `from` sesudah `to`, atau rentang lebih panjang dijawab 400 `invalid_request` dengan `param`. Hitungan tetap ada sesudah pesannya dihapus (masa simpan akun atau hapus riwayat). Tanpa `device_id`: semua device akun, termasuk yang sudah dihapus.

Scope yang dibutuhkan: `stats:read`

Parameter GET /v1/stats

| Parameter | Tipe | Wajib | Default | Keterangan |
| --- | --- | --- | --- | --- |
| `device_id` | string | tidak | — | (query) Hanya device ini (boleh device yang sudah dihapus); device akun lain dijawab 404. |
| `from` | string | tidak | — | (query) Hari pertama (YYYY-MM-DD, hari WIB); default 29 hari sebelum `to`. |
| `to` | string | tidak | — | (query) Hari terakhir, termasuk (YYYY-MM-DD, hari WIB); default hari ini. |

## Contoh request

### curl

```sh
curl https://api.gocap.id/v1/stats \
  -H 'Authorization: Bearer TOKEN_AKUN'
```

### Node.js

```javascript
async function panggil(method, path, body) {
  const res = await fetch("https://api.gocap.id" + path, {
    method,
    headers: {
      Authorization: "Bearer TOKEN_AKUN",
      ...(body ? { "Content-Type": "application/json" } : {}),
    },
    body: body ? JSON.stringify(body) : undefined,
    signal: AbortSignal.timeout(30000),
  });
  const data = res.status === 204 ? null : await res.json();
  // Error berkode HTTP 4xx/5xx dengan badan {error: {code}}.
  if (!res.ok) {
    throw new Error(`gocap menolak: ${data?.error?.code ?? res.status}`);
  }
  return data;
}

async function main() {
  console.log(await panggil("GET", "/v1/stats"));
}

main().catch((err) => {
  console.error(err.message);
  process.exitCode = 1;
});
```

### PHP

```php
<?php
function panggil(string $method, string $path, ?array $body = null): ?array
{
    $ch = curl_init('https://api.gocap.id' . $path);
    $headers = ['Authorization: Bearer TOKEN_AKUN'];
    if ($body !== null) {
        $headers[] = 'Content-Type: application/json';
    }
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST => $method,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => $body === null ? null : json_encode($body),
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 30,
    ]);
    $raw = curl_exec($ch);
    if ($raw === false) {
        echo 'Koneksi gagal: ', curl_error($ch), PHP_EOL;
        exit(1);
    }
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    $data = $raw === '' ? null : json_decode($raw, true);
    // Error berkode HTTP 4xx/5xx dengan badan {"error": {"code": ...}}.
    if ($status >= 400) {
        echo 'gocap menolak: ', $data['error']['code'] ?? $status, PHP_EOL;
        exit(1);
    }
    return $data;
}

print_r(panggil('GET', '/v1/stats'));
```

### Python

```python
import requests


def panggil(method, path, body=None):
    headers = {"Authorization": "Bearer TOKEN_AKUN"}
    res = requests.request(
        method,
        "https://api.gocap.id" + path,
        headers=headers,
        json=body,
        timeout=30,
    )
    data = None if res.status_code == 204 else res.json()
    # Error berkode HTTP 4xx/5xx dengan badan {"error": {"code": ...}}.
    if res.status_code >= 400:
        raise SystemExit(f"gocap menolak: {data['error']['code']}")
    return data


print(panggil("GET", "/v1/stats"))
```

### Go

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"time"
)

const baseURL = "https://api.gocap.id"

func panggil(method, path string, body any) (map[string]any, error) {
	var buf bytes.Buffer
	if body != nil {
		if err := json.NewEncoder(&buf).Encode(body); err != nil {
			return nil, err
		}
	}
	req, err := http.NewRequest(method, baseURL+path, &buf)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Authorization", "Bearer TOKEN_AKUN")
	if body != nil {
		req.Header.Set("Content-Type", "application/json")
	}
	client := &http.Client{Timeout: 30 * time.Second}
	res, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()
	var data map[string]any
	if res.StatusCode != http.StatusNoContent {
		if err := json.NewDecoder(res.Body).Decode(&data); err != nil {
			return nil, err
		}
	}
	// Error berkode HTTP 4xx/5xx dengan badan {"error": {"code": ...}}.
	if res.StatusCode >= 400 {
		e, _ := data["error"].(map[string]any)
		return nil, fmt.Errorf("gocap menolak: %v", e["code"])
	}
	return data, nil
}

func cetak(data map[string]any, err error) {
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
	fmt.Println(data)
}

func main() {
	cetak(panggil("GET", "/v1/stats", nil))
}
```

## Contoh response

Contoh response 200 (Statistik rentang itu.)

```json
{
  "from": "2026-10-07",
  "to": "2026-10-08",
  "device_id": null,
  "days": [
    {
      "day": "2026-10-07",
      "in": 12,
      "out": {
        "sent": 40,
        "invalid": 1,
        "failed": 2,
        "expired": 0,
        "pending": 0
      },
      "quota": 43
    },
    {
      "day": "2026-10-08",
      "in": 5,
      "out": {
        "sent": 18,
        "invalid": 0,
        "failed": 0,
        "expired": 0,
        "pending": 3
      },
      "quota": 21
    }
  ],
  "totals": {
    "in": 17,
    "out": {
      "sent": 58,
      "invalid": 1,
      "failed": 2,
      "expired": 0,
      "pending": 3
    },
    "quota": 64
  }
}
```

## Contoh error

Contoh error 400 (Rentang terlalu panjang)

```json
{
  "error": {
    "code": "invalid_request",
    "message": "Rentang from sampai to paling panjang 366 hari.",
    "param": "from",
    "request_id": "0199d9d5-6a2e-7c3f-9b4d-1e2f3a4b5c6d"
  }
}
```

## Response

| Kode | Arti | Body |
| --- | --- | --- |
| `200` | Statistik rentang itu. | `Stats` |
| `400` | Permintaan salah bentuk — kode `invalid_request` (lihat `x-error-codes`). | `Error` |
| `401` | API key tidak ada atau tidak dikenal. | `Error` |
| `403` | API key tidak punya scope operasi ini (`insufficient_scope`), atau dipakai dari IP di luar daftar IP kunci (`ip_not_allowed`). | `Error` |
| `404` | Resource tidak ada atau milik akun lain. | `Error` |
| `429` | Batas laju terlampaui. | `Error` |
| `500` | Kegagalan di sisi gocap. | `Error` |

Field response 200 GET /v1/stats

| Field | Tipe | Isi |
| --- | --- | --- |
| `from` | string | Hari pertama rentang (WIB). |
| `to` | string | Hari terakhir rentang, termasuk (WIB). |
| `device_id` | string atau `null` | Device yang dihitung; `null` = semua device akun, termasuk yang sudah dihapus. |
| `days` | array objek | Satu entri per hari dari `from` sampai `to`, urut naik; hari tanpa pesan bernilai nol. |
| `days[].day` | string | Tanggal WIB (YYYY-MM-DD). |
| `days[].in` | integer | Pesan masuk. |
| `days[].out` | objek | Pesan keluar per status akhir. |
| `days[].quota` | integer | Quota terpakai = jumlah pesan keluar hari itu (satu pesan satu Quota). |
| `totals` | objek | Jumlah seluruh rentang. |
| `totals.in` | integer | Pesan masuk. |
| `totals.out` | objek | Pesan keluar per status akhir. |
| `totals.quota` | integer | Quota terpakai. |

## Error

Error dijawab dengan kode HTTP di tabel response dan body `{"error":{"code":"…","message":"…","request_id":"…"}}`; arti setiap kode ada di [Kode error /v1](https://app.gocap.id/docs/referensi/v1/galat).

| Kode | HTTP | Arti |
| --- | --- | --- |
| [`invalid_request`](https://app.gocap.id/docs/referensi/v1/galat#invalid-request) | 400 | Permintaan salah bentuk: parameter, header, atau badan JSON tidak dapat dibaca, atau memuat field yang tidak dikenal; `param` menyebut bagiannya bila diketahui. |
| [`not_found`](https://app.gocap.id/docs/referensi/v1/galat#not-found) | 404 | Path tidak ada; resource tidak ada, sudah dihapus, milik akun lain, atau di luar daftar device kunci (`param` menyebut id-nya); atau pengulangan Idempotency-Key suatu operasi buat yang resource hasilnya sudah dihapus (jawaban diputar ulang membaca resource terkini). |

Error umum (401/403/405/429/500) berlaku untuk semua operasi; daftarnya di [Kode error /v1](https://app.gocap.id/docs/referensi/v1/galat).
