Usage & Cost Tracking Basics
9 examples to get you started with Usage & Cost Tracking - 6 basic and 3 intermediate.
Prerequisites
- Install the SDK:
pip install anthropic. - Generate an admin API key from the Claude Console (a regular API key cannot call Admin API endpoints).
- Set
ANTHROPIC_ADMIN_KEYas an environment variable rather than hardcoding it in your script.
Basic Examples
1. Fetch a Usage Report
Pull raw token usage for the last 7 days with no grouping.
import anthropic
from datetime import datetime, timedelta, timezone
client = anthropic.Anthropic(api_key=None) # picks up ANTHROPIC_ADMIN_KEY
start = (datetime.now(timezone.utc) - timedelta(days=7)).isoformat()
report = client.beta.usage.report(starting_at=start)
for bucket in report.data:
print(bucket.uncached_input_tokens, bucket.output_tokens)report()returns time-bucketed usage records, not one flat total.- Each record separates
uncached_input_tokens,cached_input_tokens,cache_creation_input_tokens, andoutput_tokens. - Without a
group_by, results are aggregated across your whole organization.
2. Fetch a Cost Report
Pull the dollar-denominated view of the same window.
import anthropic
client = anthropic.Anthropic()
cost = client.beta.cost.report(starting_at="2026-06-01T00:00:00Z")
for bucket in cost.data:
print(bucket.amount, bucket.currency)- The cost endpoint mirrors the usage endpoint's shape but returns dollar amounts instead of token counts.
- Cost is derived from usage at the platform's current pricing, not a separate manual entry.
- Use the cost endpoint when you just need a dollar total; use usage when you need to explain why.
3. Filter by a Single Workspace
Narrow a report down to one workspace ID.
import anthropic
client = anthropic.Anthropic()
report = client.beta.usage.report(
starting_at="2026-06-01T00:00:00Z",
workspace_ids=["wksp_01abc123"],
)workspace_idsaccepts a list, so you can filter to one or several workspaces in a single call.- Find workspace IDs in the Console under Organization settings, or by listing workspaces with the Admin API.
- Omitting this filter returns usage across every workspace you have access to.
4. Group Usage by Workspace
See every workspace's usage side by side, instead of filtering to one.
import anthropic
client = anthropic.Anthropic()
report = client.beta.usage.report(
starting_at="2026-06-01T00:00:00Z",
group_by=["workspace_id"],
)
for bucket in report.data:
print(bucket.workspace_id, bucket.output_tokens)group_byreturns one row per unique value of the grouping key, similar to SQL'sGROUP BY.- Grouping by
workspace_idis the fastest way to see which team is driving usage. - You can combine multiple grouping keys in one list, for example
["workspace_id", "model"].
5. Set a Time Range with an End Date
Bound a report to a specific window instead of "everything since a start date."
import anthropic
client = anthropic.Anthropic()
report = client.beta.usage.report(
starting_at="2026-06-01T00:00:00Z",
ending_at="2026-06-30T23:59:59Z",
)ending_atis optional; omitting it defaults to "now."- Both timestamps are ISO 8601 and interpreted in UTC.
- A bounded window is what you want for a monthly report that shouldn't shift as new days pass.
6. Choose a Time Bucket Granularity
Control whether results come back per day, per hour, or as one summed total.
import anthropic
client = anthropic.Anthropic()
report = client.beta.usage.report(
starting_at="2026-06-01T00:00:00Z",
ending_at="2026-06-08T00:00:00Z",
bucket_width="1d",
)
for bucket in report.data:
print(bucket.starting_at, bucket.output_tokens)bucket_widthcontrols how usage is time-sliced within your window, for example"1h"or"1d".- A finer bucket width gives you a trend line; a coarse one gives you a single summary figure.
- Pick the width to match how you plan to chart the data, not just the widest option available.
Related: How the Usage & Cost Admin API Models Your Spend - the token-bucket model behind these fields
Intermediate Examples
7. Combine Workspace Filter with Model Grouping
Answer "which models is this workspace using, and how much do they cost" in one call.
import anthropic
client = anthropic.Anthropic()
report = client.beta.usage.report(
starting_at="2026-06-01T00:00:00Z",
workspace_ids=["wksp_01abc123"],
group_by=["model"],
)
for bucket in report.data:
total_input = bucket.uncached_input_tokens + bucket.cached_input_tokens
print(bucket.model, total_input, bucket.output_tokens)- Filters (
workspace_ids) and grouping (group_by) compose freely in the same request. - Summing
uncached_input_tokensandcached_input_tokensgives you total input volume, while keeping them visible separately preserves the cost story. - This pattern is the starting point for a per-workspace, per-model cost report.
8. Paginate Through a Large Report
Walk every page of a report that spans more data than fits in one response.
import anthropic
client = anthropic.Anthropic()
report = client.beta.usage.report(
starting_at="2026-01-01T00:00:00Z",
group_by=["api_key_id", "model"],
)
all_buckets = list(report.data)
while report.has_next_page():
report = report.get_next_page()
all_buckets.extend(report.data)
print(len(all_buckets), "usage buckets fetched")- Wide date ranges combined with fine-grained
group_bykeys can produce many rows, so pagination is common in practice. - The SDK's page object exposes
has_next_page()andget_next_page()so you don't hand-roll cursor logic. - Always accumulate into your own list or database; the SDK's page objects are not meant to be held onto indefinitely.
9. Roll Up Cost by Token Type
Compute a per-token-type cost total from a single report, the first step toward a real dashboard.
import anthropic
from collections import defaultdict
client = anthropic.Anthropic()
report = client.beta.usage.report(
starting_at="2026-06-01T00:00:00Z",
group_by=["model"],
)
totals = defaultdict(int)
for bucket in report.data:
totals["uncached_input"] += bucket.uncached_input_tokens
totals["cached_input"] += bucket.cached_input_tokens
totals["cache_creation"] += bucket.cache_creation_input_tokens
totals["output"] += bucket.output_tokens
for token_type, count in totals.items():
print(token_type, count)defaultdict(int)avoidsKeyErrors while accumulating counts across many buckets.- This is the raw shape a finance-facing dashboard needs before it applies pricing per token type.
- Keeping the four token types separate here, rather than summing them into one number, is what preserves the ability to explain the total later.
Related: Building a Cost Dashboard from Uncached, Cached, and Output Token Breakdowns - the full dashboard this pattern leads to | Querying Usage by API Key and Workspace with the Admin API - narrower, single-key and single-workspace queries
Stack versions: Written against the Claude model lineup current as of ~June 2026 - Claude Fable 5, Claude Opus 4.8, Claude Sonnet 5 (the default), and Claude Haiku 4.5 - and the official
anthropicPython SDK (latest 0.x release). Model names, pricing, and SDK versions move quickly - verify current specifics at platform.claude.com/docs before relying on them.