# Claude API for measuring a request before generation

[Originally published on Medium](https://medium.com/p/14e40113c731)

A support team may assemble a prompt from a system policy, a PDF manual, the latest customer message, and several tool definitions. The final JSON can be much larger than the text visible in the chat box. Sending it first and measuring later is like weighing a parcel after it has left the warehouse.

The Claude API on [Ace Data Cloud](https://platform.acedata.cloud?utm_source=hashnode&utm_medium=article&utm_campaign=claude-api-overview) gives us a useful preflight step. We can count the input tokens in the complete request at zero credits, then submit the message through the native Claude format. That makes token budgeting part of request construction instead of a surprise in the usage record.

## Choose the native shape or the familiar chat shape

[Claude AI on Ace Data Cloud](https://platform.acedata.cloud?utm_source=hashnode&utm_medium=article&utm_campaign=claude-api-overview) exposes two generation formats and one counting operation.

The [Claude Messages API](https://platform.acedata.cloud/documents/claude-messages-integration?utm_source=hashnode&utm_medium=article&utm_campaign=claude-api-overview) uses Anthropic's native message structure at `POST /claude/messages`. It accepts `model`, `messages`, and `max_tokens` as the core generation fields. It also supports a top-level `system` prompt, streaming, tools, images, documents, prompt caching, and thinking configuration.

The [Claude Chat Completions API](https://platform.acedata.cloud/documents/claude-chat-completions?utm_source=hashnode&utm_medium=article&utm_campaign=claude-api-overview) is available at `POST /claude/chat/completions`. Its OpenAI-compatible shape is useful when an application already expects chat completions.

The preflight endpoint is `POST /claude/messages/count_tokens`. Its request mirrors the native Messages input closely, so we can count a payload containing much more than a plain string.

## Send a native message

The smallest useful native request contains a model, an output limit, and a user message. Authentication uses an [Ace Data Cloud](https://platform.acedata.cloud?utm_source=hashnode&utm_medium=article&utm_campaign=claude-api-overview) bearer token.

```bash
curl -X POST 'https://api.acedata.cloud/claude/messages' \
  -H 'accept: application/json' \
  -H 'authorization: Bearer YOUR_API_TOKEN' \
  -H 'content-type: application/json' \
  -d '{
    "model": "claude-opus-4-8",
    "max_tokens": 1024,
    "messages": [
      {
        "role": "user",
        "content": "Hello, Claude"
      }
    ]
  }'
```

A non-streaming response has the native Claude message shape:

```json
{
  "id": "msg_013Zva2CMHLNnXjNJJKqJ2EF",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Hi! My name is Claude. How can I help you today?"
    }
  ],
  "model": "claude-opus-4-8",
  "stop_reason": "end_turn",
  "stop_sequence": null,
  "usage": {
    "input_tokens": 12,
    "output_tokens": 15
  }
}
```

`id` uniquely identifies the returned message. `type` is `message`, and `role` is `assistant`. `content` is an array because a reply can contain typed blocks rather than one undifferentiated string. Here the block has `type: text`, and `text` contains the answer.

`model` records which model handled the request. `stop_reason` explains why generation ended. `end_turn` means the model completed its turn. Other documented values include `max_tokens`, `stop_sequence`, `tool_use`, `pause_turn`, `refusal`, and `model_context_window_exceeded`. `stop_sequence` is null here because no custom sequence ended the reply.

`usage.input_tokens` reports uncached input tokens, while `usage.output_tokens` reports generated tokens. Responses can also report cache creation and cache read token counts when caching is involved. Non-streaming responses may include the cost recorded by [Ace Data Cloud](https://platform.acedata.cloud?utm_source=hashnode&utm_medium=article&utm_campaign=claude-api-overview).

## Count the payload that will actually be sent

The token counter becomes useful when the payload grows. We can send `model` and `messages`, then include the same optional structures our generation request will use. The schema supports `system`, `tools`, `tool_choice`, `thinking`, and `cache_control`.

Message content can also include typed blocks. Image blocks accept Base64 data or a URL, with JPEG, PNG, GIF, and WebP media types. Document blocks can carry a Base64 PDF, a PDF URL, plain text, or content made from text and image blocks. The token count therefore reflects the assembled API request rather than a rough character estimate.

```bash
curl -X POST 'https://api.acedata.cloud/claude/messages/count_tokens' \
  -H 'accept: application/json' \
  -H 'authorization: Bearer YOUR_API_TOKEN' \
  -H 'content-type: application/json' \
  -d '{
    "model": "claude-opus-4-8",
    "system": "Answer from the supplied reference material.",
    "messages": [
      {
        "role": "user",
        "content": "Summarize the deployment rules."
      }
    ]
  }'
```

The successful response contains `input_tokens`, an integer with the calculated input count. The endpoint does not generate assistant text. We bill this operation at **0 credits**. The Claude service itself includes **1.0 free credit**, while generation is billed in credits according to the selected model and measured token usage.

For a current price reference, `claude-opus-5` is listed at **10.5124 credits per 1 million input tokens** and **52.5618 credits per 1 million output tokens**. Its listed capabilities include reasoning and vision. Prices differ by model, so production code should read the current catalog rather than copy one model's rate into a permanent constant.

## The counter understands more than text

A common token helper accepts a string and returns an estimate. This endpoint accepts the request structures that materially affect a Claude call. We can count tool definitions before exposing them to the model. We can include a document block with optional `title`, `context`, and citation settings. We can represent an image as a URL or Base64 source. We can also include cache controls.

Top-level `cache_control` places a cache breakpoint at the last cacheable block. Its `ttl` supports `5m`, which is the default, and `1h`. For precise placement, cache control can be attached to text, image, document, tool-use, tool-result blocks, or tool definitions. Generation usage then distinguishes `cache_creation_input_tokens` from `cache_read_input_tokens`.

Thinking settings belong in the same planning process. Current models can use `thinking.type: adaptive`, with `output_config.effort` controlling reasoning effort. When `display` is `summarized`, the response can contain a readable thinking summary. When it is `omitted`, reasoning still occurs, but returned thinking text is empty and the opaque signature remains available for later turns. Display selection does not reduce billing for thinking tokens.

## Put preflight counting in the request path

We can build one payload object, send its countable fields to `/claude/messages/count_tokens`, compare `input_tokens` with our application budget, and then send the generation request to `/claude/messages`. If the count is too high, the application can shorten retrieved context or remove unnecessary tool descriptions before it pays for generation.

Keep `max_tokens` as an explicit generation limit, preserve prior `assistant` and `user` turns in order, and pass returned thinking blocks and signatures back unchanged when the workflow requires them. For streaming interfaces, set `stream` to true and consume Server-Sent Events such as `message_start`, `content_block_delta`, `message_delta`, and `message_stop`.

Create one token in the [Ace Data Cloud console](https://platform.acedata.cloud/console/applications?utm_source=hashnode&utm_medium=article&utm_campaign=claude-api-overview), use the free counter on the full payload your application has assembled, and send the approved structure to the native Messages endpoint. The count request costs zero, so it can sit directly in the validation path instead of being reserved for occasional debugging.

Sources: [Anthropic Messages API](https://platform.claude.com/docs/en/api/messages), [Anthropic token counting](https://platform.claude.com/docs/en/build-with-claude/token-counting)

Tags: Claude API, Anthropic, API Development, Artificial Intelligence, Software Engineering

