Skip to content
Software capabilities
Anthropic Claude API

Count Claude message input tokens

Count the input tokens for a Messages API request before sending it. Use the token-count endpoint directly or call it through an Anthropic SDK.

Documentation reviewed · 2 methods with sources

Ways to do it

  1. API: POST /v1/messages/count_tokens
  2. SDK: client.messages.count_tokens()
API

POST /v1/messages/count_tokens

Send the model and message inputs to estimate the request's input-token count.

Read source: Anthropic count tokens API reference
Requirements
An Anthropic API key, the required API version header, a supported model, and the message input to count.
Limitations
This estimates input tokens and does not apply prompt caching. Server tools (except the advisor tool), MCP connectors, and URL- or file-sourced image and document blocks are rejected. Use base64 for image and PDF content.

Example shell

curl https://api.anthropic.com/v1/messages/count_tokens \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2026-10-21" \
  -H "content-type: application/json" \
  -d '{"model":"claude-opus-5-5","messages":[{"role":"user","content":"Hello, Claude"}]}'
SDK

client.messages.count_tokens()

Count the tokens in a structured message using the Anthropic Python SDK.

Read source: Anthropic token counting guide
Requirements
The Anthropic Python SDK initialized with an API key, a supported model, and the messages to count.
Limitations
Counts are an estimate for the specified model. Inputs unsupported by the counting endpoint must be removed or represented in a supported form.

Example text

count = client.messages.count_tokens(model="claude-opus-5-5", messages=[{"role": "user", "content": "Hello, Claude"}])