> This page is for Gateway.

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.merge.dev/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.merge.dev/_mcp/server.

# Count tokens in a message

POST https://api-gateway.merge.dev/v1/messages/count_tokens
Content-Type: application/json

Counts the input tokens a Messages request would consume, without calling a model.

Also served at `/v1/anthropic/v1/messages/count_tokens`; both paths accept the same requests.

Reference: https://docs.merge.dev/merge-gateway/api-overview/messages/count-tokens

## Authentication

- `Authorization` header (bearer token, required) — Your production key sent as a bearer token.

## Request

### Body (application/json)

This endpoint expects an AnthropicCountTokensRequest.

- `model` (string, required)
- `messages` (list of AnthropicMessageParam, required)
- `system` (AnthropicCountTokensRequestSystem, optional, nullable)
- `tools` (list of AnthropicToolDef, optional, nullable)
- `tool_choice` (map from string to any, optional, nullable) — Tool choice, counted as part of the prompt.
- `thinking` (AnthropicThinkingConfig, optional, nullable) — Extended thinking settings for models that support it.

## Response

### 200

Successful Response

- `input_tokens` (integer, required)

## Errors

### 422 Unprocessable Entity Error

Validation Error

- `detail` (list of ValidationError, optional)

## Types

### AnthropicMessageParam

- `role` (enum, required)
  - Allowed values: `user`, `assistant`
- `content` (AnthropicMessageParamContent, required)

### AnthropicCountTokensRequestSystem

- string
- list of AnthropicContentBlock

### AnthropicToolDef

- `name` (string, required)
- `description` (string, optional, nullable)
- `input_schema` (map from string to any, optional)
- `type` (string, optional, nullable) — Tool type for Anthropic server tools; omit for a custom tool.
- `defer_loading` (boolean, optional, nullable) — Load this tool on demand through tool search instead of sending it with every request.

### AnthropicThinkingConfig

Anthropic extended thinking settings, accepting both the `enabled` with `budget_tokens` form and `adaptive`.

- `type` (string, optional, default: enabled) — Thinking mode, for example `enabled` or `adaptive`.
- `budget_tokens` (integer, optional, default: 10000) — Maximum tokens the model may spend thinking.
- `display` (string, optional, nullable)
- `block_binding` (map from string to any, optional, nullable)

### ValidationError

Single field-level validation error. `loc` is the JSON path to the offending field, `msg` is a human-readable explanation, and `type` is a stable machine-readable error code.

- `loc` (list of ValidationErrorLocItems, required)
- `msg` (string, required)
- `type` (string, required)
- `input` (any, optional)
- `ctx` (ValidationErrorCtx, optional)

### AnthropicMessageParamContent

- string
- list of AnthropicContentBlock

### AnthropicContentBlock

- `type` (string, required) — Block type, such as `text`, `image`, `tool_use`, or `tool_result`
- `text` (string, optional, nullable)
- `id` (string, optional, nullable)
- `name` (string, optional, nullable)
- `input` (map from string to any, optional, nullable)
- `tool_use_id` (string, optional, nullable)
- `content` (AnthropicContentBlockContent, optional, nullable)
- `source` (map from string to any, optional, nullable)
- `is_error` (boolean, optional, nullable) — Marks a `tool_result` block as an error.
- `thinking` (string, optional, nullable) — Reasoning text of a `thinking` block.
- `cache_control` (map from string to any, optional, nullable) — Marks a prompt-caching breakpoint at this block for providers that support it.

### ValidationErrorLocItems

- string
- integer

### ValidationErrorCtx

### AnthropicContentBlockContent

- string
- list of any

## Examples

**Request**

```json
{
  "model": "anthropic/claude-sonnet-5",
  "messages": [
    {
      "role": "user",
      "content": "What is the capital of France?"
    }
  ]
}
```

**Response**

```json
{
  "input_tokens": 14
}
```

**SDK Code**

```python
import requests

url = "https://api-gateway.merge.dev/v1/messages/count_tokens"

payload = {
    "model": "anthropic/claude-sonnet-5",
    "messages": [
        {
            "role": "user",
            "content": "What is the capital of France?"
        }
    ]
}
headers = {
    "Authorization": "Bearer <token>",
    "Content-Type": "application/json"
}

response = requests.post(url, json=payload, headers=headers)

print(response.json())
```

```javascript
const url = 'https://api-gateway.merge.dev/v1/messages/count_tokens';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"anthropic/claude-sonnet-5","messages":[{"role":"user","content":"What is the capital of France?"}]}'
};

try {
  const response = await fetch(url, options);
  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error(error);
}
```

```go
package main

import (
	"fmt"
	"strings"
	"net/http"
	"io"
)

func main() {

	url := "https://api-gateway.merge.dev/v1/messages/count_tokens"

	payload := strings.NewReader("{\n  \"model\": \"anthropic/claude-sonnet-5\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"What is the capital of France?\"\n    }\n  ]\n}")

	req, _ := http.NewRequest("POST", url, payload)

	req.Header.Add("Authorization", "Bearer <token>")
	req.Header.Add("Content-Type", "application/json")

	res, _ := http.DefaultClient.Do(req)

	defer res.Body.Close()
	body, _ := io.ReadAll(res.Body)

	fmt.Println(res)
	fmt.Println(string(body))

}
```

```ruby
require 'uri'
require 'net/http'

url = URI("https://api-gateway.merge.dev/v1/messages/count_tokens")

http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true

request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n  \"model\": \"anthropic/claude-sonnet-5\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"What is the capital of France?\"\n    }\n  ]\n}"

response = http.request(request)
puts response.read_body
```

```java
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;

HttpResponse<String> response = Unirest.post("https://api-gateway.merge.dev/v1/messages/count_tokens")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"anthropic/claude-sonnet-5\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"What is the capital of France?\"\n    }\n  ]\n}")
  .asString();
```

```php
<?php
require_once('vendor/autoload.php');

$client = new \GuzzleHttp\Client();

$response = $client->request('POST', 'https://api-gateway.merge.dev/v1/messages/count_tokens', [
  'body' => '{
  "model": "anthropic/claude-sonnet-5",
  "messages": [
    {
      "role": "user",
      "content": "What is the capital of France?"
    }
  ]
}',
  'headers' => [
    'Authorization' => 'Bearer <token>',
    'Content-Type' => 'application/json',
  ],
]);

echo $response->getBody();
```

```csharp
using RestSharp;

var client = new RestClient("https://api-gateway.merge.dev/v1/messages/count_tokens");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer <token>");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("application/json", "{\n  \"model\": \"anthropic/claude-sonnet-5\",\n  \"messages\": [\n    {\n      \"role\": \"user\",\n      \"content\": \"What is the capital of France?\"\n    }\n  ]\n}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
```

```swift
import Foundation

let headers = [
  "Authorization": "Bearer <token>",
  "Content-Type": "application/json"
]
let parameters = [
  "model": "anthropic/claude-sonnet-5",
  "messages": [
    [
      "role": "user",
      "content": "What is the capital of France?"
    ]
  ]
] as [String : Any]

let postData = JSONSerialization.data(withJSONObject: parameters, options: [])

let request = NSMutableURLRequest(url: NSURL(string: "https://api-gateway.merge.dev/v1/messages/count_tokens")! as URL,
                                        cachePolicy: .useProtocolCachePolicy,
                                    timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data

let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
  if (error != nil) {
    print(error as Any)
  } else {
    let httpResponse = response as? HTTPURLResponse
    print(httpResponse)
  }
})

dataTask.resume()
```