> ## Documentation Index
> Fetch the complete documentation index at: https://docs.opsmatic.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Usage & Cost API

> Push and query token usage and cost estimates for n8n, Make.com, and custom workloads

## Overview

Opsmatic tracks AI usage and cost from two sources:

<CardGroup cols={2}>
  <Card title="OpenClaw (automatic)" icon="robot" href="/connections/openclaw-setup">
    The OpenClaw daemon pushes token usage and costs with every heartbeat — no API calls needed. See the [OpenClaw setup guide](/connections/openclaw-setup#how-costs-are-calculated) for how those costs are calculated.
  </Card>

  <Card title="Usage API (this page)" icon="code">
    For **n8n**, Make.com, and custom workloads, your workflows report token usage and cost estimates themselves via `POST /v1/usage` — typically from an HTTP Request node at the end of an AI workflow.
  </Card>
</CardGroup>

The Usage API lets you attribute AI spend to the workflows and executions that produced it, then query it back raw or aggregated.

## Authentication & Permissions

All endpoints use a standard API key (`Authorization: Bearer ops_...`). The key needs:

| Operation                        | Required permission |
| -------------------------------- | ------------------- |
| `POST /v1/usage`                 | `usage: write`      |
| `GET /v1/usage`, `PUT /v1/usage` | `usage: read`       |

The key must also have access to the connection each entry references — personal keys cover your own connections and those of organizations you belong to.

## Push Usage Entries

```
POST /v1/usage
```

Accepts a single entry or a batch (array, max **100 entries** per request).

### Entry Fields

| Field           | Type                 | Required      | Description                                                                                            |
| --------------- | -------------------- | ------------- | ------------------------------------------------------------------------------------------------------ |
| `connection_id` | string               | Yes           | The Opsmatic connection this usage belongs to (e.g. your n8n connection)                               |
| `entity`        | string               | Yes           | What consumed the usage — a model name (`gpt-4o`), service, or component                               |
| `usage_amount`  | number               | Yes           | The quantity consumed — token count for `tokens` entries                                               |
| `usage_entity`  | `tokens` \| `custom` | No            | Defaults to `tokens`. Use `custom` with `custom_name` for non-token units (API calls, minutes, images) |
| `custom_name`   | string               | With `custom` | Name of the custom unit being counted                                                                  |
| `cost_cents`    | number               | No            | Cost estimate in **cents** (e.g. `12` = \$0.12). Defaults to 0                                         |
| `workflow_id`   | string               | No            | The n8n/Make workflow that produced the usage                                                          |
| `execution_id`  | string               | No            | The specific execution, for per-run attribution                                                        |
| `metadata`      | object               | No            | Any extra context (model parameters, user, environment)                                                |

### Example — single entry

```bash theme={null}
curl -X POST https://api.opsmatic.com/v1/usage \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "connection_id": "conn_abc123",
    "workflow_id": "wf_support_triage",
    "execution_id": "exec_20260706_1432",
    "entity": "gpt-4o",
    "usage_entity": "tokens",
    "usage_amount": 4820,
    "cost_cents": 3,
    "metadata": { "prompt_tokens": 3900, "completion_tokens": 920 }
  }'
```

### Example — batch

```bash theme={null}
curl -X POST https://api.opsmatic.com/v1/usage \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '[
    { "connection_id": "conn_abc123", "entity": "gpt-4o", "usage_amount": 4820, "cost_cents": 3 },
    { "connection_id": "conn_abc123", "entity": "claude-sonnet-4-5", "usage_amount": 12100, "cost_cents": 9 }
  ]'
```

Responses return `201` with the inserted entries. Validation failures return `400` with a per-index `validation_errors` array — in a batch, one invalid entry rejects the whole request, so fix and resend.

## Reporting Token Usage from n8n

The recommended pattern: add an **HTTP Request node** after your AI/LLM node and map the token usage the node already exposes.

<Steps>
  <Step title="Capture token counts from the AI node">
    Most n8n AI nodes (OpenAI, Anthropic, AI Agent) return token usage in their output — typically under `tokenUsage` or `usage` with prompt/completion/total token counts. Check your node's output panel for the exact path.
  </Step>

  <Step title="Estimate the cost">
    Multiply tokens by your model's rates. Example expression for GPT-4o ($2.50/M input, $10/M output), producing **cents**:

    ```
    {{ Math.round(($json.tokenUsage.promptTokens * 2.50 + $json.tokenUsage.completionTokens * 10.00) / 1000000 * 100) }}
    ```
  </Step>

  <Step title="Add an HTTP Request node">
    * **Method**: POST
    * **URL**: `https://api.opsmatic.com/v1/usage`
    * **Authentication**: Header Auth — `Authorization: Bearer YOUR_API_KEY`
    * **Body** (JSON):

    ```json theme={null}
    {
      "connection_id": "conn_abc123",
      "workflow_id": "{{ $workflow.id }}",
      "execution_id": "{{ $execution.id }}",
      "entity": "gpt-4o",
      "usage_entity": "tokens",
      "usage_amount": "{{ $json.tokenUsage.totalTokens }}",
      "cost_cents": "{{ Math.round(($json.tokenUsage.promptTokens * 2.50 + $json.tokenUsage.completionTokens * 10.00) / 1000000 * 100) }}",
      "metadata": {
        "prompt_tokens": "{{ $json.tokenUsage.promptTokens }}",
        "completion_tokens": "{{ $json.tokenUsage.completionTokens }}"
      }
    }
    ```
  </Step>

  <Step title="Verify in Opsmatic">
    Entries appear in the connection's usage data immediately — query them with `GET /v1/usage?connection_id=conn_abc123` or view them in Analytics.
  </Step>
</Steps>

<Tip>
  Use `{{ $workflow.id }}` and `{{ $execution.id }}` so every entry is attributable to the exact run that spent the tokens — that's what makes per-workflow cost breakdowns possible later.
</Tip>

<Note>
  If your workflow calls multiple models, send a **batch** with one entry per model rather than a single summed entry — per-model attribution is lost once counts are merged.
</Note>

## Query Usage Entries

```
GET /v1/usage
```

Returns raw entries, newest first, scoped to connections your key can access.

### Query Parameters

| Parameter                 | Description                          |
| ------------------------- | ------------------------------------ |
| `connection_id`           | Filter to one connection             |
| `workflow_id`             | Filter to one workflow               |
| `execution_id`            | Filter to one execution              |
| `entity`                  | Filter by entity (e.g. `gpt-4o`)     |
| `usage_entity`            | `tokens` or `custom`                 |
| `start_date` / `end_date` | ISO timestamps bounding `created_at` |
| `limit`                   | Page size, max 100 (default 50)      |
| `offset`                  | Pagination offset                    |

```bash theme={null}
curl -H "Authorization: Bearer YOUR_API_KEY" \
  "https://api.opsmatic.com/v1/usage?connection_id=conn_abc123&usage_entity=tokens&start_date=2026-07-01T00:00:00Z"
```

Response:

```json theme={null}
{
  "usage_data": [
    {
      "connection_id": "conn_abc123",
      "workflow_id": "wf_support_triage",
      "execution_id": "exec_20260706_1432",
      "entity": "gpt-4o",
      "usage_entity": "tokens",
      "usage_amount": 4820,
      "cost_cents": 3,
      "created_at": "2026-07-06T14:32:11Z"
    }
  ],
  "pagination": { "total": 1, "limit": 50, "offset": 0, "has_more": false }
}
```

## Aggregated Summaries

```
PUT /v1/usage?connection_id=conn_abc123
```

Returns rolled-up totals instead of raw entries. `connection_id` is required.

* **Connection summary** — pass `connection_id` alone (optionally `start_date` / `end_date`; defaults to the last 30 days) for totals across the connection.
* **Execution summary** — pass `workflow_id` **and** `execution_id` for the totals of a single run.

```bash theme={null}
# What did this specific execution cost?
curl -X PUT -H "Authorization: Bearer YOUR_API_KEY" \
  "https://api.opsmatic.com/v1/usage?connection_id=conn_abc123&workflow_id=wf_support_triage&execution_id=exec_20260706_1432"
```

## Related

<CardGroup cols={2}>
  <Card title="OpenClaw Cost Tracking" icon="robot" href="/connections/openclaw-setup#how-costs-are-calculated">
    Automatic token and cost monitoring for OpenClaw gateways, including budget alerts
  </Card>

  <Card title="API Introduction" icon="book" href="/api-reference/introduction">
    Authentication, rate limits, and error handling for all API endpoints
  </Card>
</CardGroup>
