---
title: "Count message tokens (Anthropic format)"
description: "Counts the input tokens of a Messages request without running it, as Anthropic's count tokens API does. It is served under `/api`, so set the Anthropic SDK's `base_url` to `https://gateway.respan.ai/api` for `client.messages.count_tokens()` to reach it."
---

**POST** `https://gateway.respan.ai/api/v1/messages/count_tokens`

Counts the input tokens of a Messages request without running it, as Anthropic's count tokens API does. It is served under `/api`, so set the Anthropic SDK's `base_url` to `https://gateway.respan.ai/api` for `client.messages.count_tokens()` to reach it.

## Servers

`https://gateway.respan.ai`: Respan gateway

## Authentication

### RespanApiKey

Use your Respan API key for Respan API authentication. Enter only the Respan API key value; clients send Authorization: Bearer &lt;RESPAN_API_KEY&gt;. For /api/responses, provider credentials such as Perplexity, OpenAI, or Azure OpenAI go in Settings -&gt; Providers or respan_params.credential_override in the request body, not in this authentication field.

HTTP scheme: `bearer`; format: `Respan API key`.


```http
Authorization: Bearer $RESPAN_API_KEY
```


## Headers


| Parameter | Type | Required | Description and constraints |
| --- | --- | --- | --- |
| `x-api-key` | `string` | Optional | Your Respan API key, as the Anthropic SDK sends it. `Authorization: Bearer` also works.<br />Example: `"YOUR_RESPAN_API_KEY"` |
| `anthropic-version` | `string` | Optional | Default: `2023-06-01` |


## Request body

A request body is required.

### application/json


| Field | Type | Requirement | Description and constraints |
| --- | --- | --- | --- |
| `$` | `object` | Required body | Additional properties are allowed |
| `model` | `string` | Required in parent | - |
| `messages` | `array<object>` | Required in parent | - |
| `messages[]` | `object` | Array item | Additional properties are allowed |
| `system` | `string or array<object>` | Optional | - |
| `system (oneOf 1)` | `string` | Schema variant | - |
| `system (oneOf 2)` | `array<object>` | Schema variant | - |
| `system (oneOf 2)[]` | `object` | Array item | Additional properties are allowed |
| `tools` | `array<object>` | Optional | - |
| `tools[]` | `object` | Array item | Additional properties are allowed |


<details class="api-schema-source">
<summary>OpenAPI request schema</summary>


```json
{
  "type": "object",
  "required": [
    "model",
    "messages"
  ],
  "additionalProperties": true,
  "properties": {
    "model": {
      "type": "string"
    },
    "messages": {
      "type": "array",
      "items": {
        "type": "object",
        "additionalProperties": true
      }
    },
    "system": {
      "oneOf": [
        {
          "type": "string"
        },
        {
          "type": "array",
          "items": {
            "type": "object",
            "additionalProperties": true
          }
        }
      ]
    },
    "tools": {
      "type": "array",
      "items": {
        "type": "object",
        "additionalProperties": true
      }
    }
  }
}
```

</details>

##### Example


```json
{
  "model": "claude-haiku-4-5",
  "messages": [
    {
      "role": "user",
      "content": "Hello"
    }
  ]
}
```


## Examples

### Count tokens

#### Headers


```json
{
  "x-api-key": "YOUR_RESPAN_API_KEY",
  "anthropic-version": "2023-06-01"
}
```


#### Request


```json
{
  "model": "claude-haiku-4-5",
  "messages": [
    {
      "role": "user",
      "content": "Hello"
    }
  ]
}
```


#### Response


```json
{
  "body": {
    "input_tokens": 8
  }
}
```


#### cURL


```bash
curl --request POST 'https://gateway.respan.ai/api/v1/messages/count_tokens' \
  --header "Authorization: Bearer $RESPAN_API_KEY" \
  --header 'x-api-key: YOUR_RESPAN_API_KEY' \
  --header 'anthropic-version: 2023-06-01' \
  --header 'Content-Type: application/json' \
  --data @- <<'JSON'
{
  "model": "claude-haiku-4-5",
  "messages": [
    {
      "role": "user",
      "content": "Hello"
    }
  ]
}
JSON
```


<details>
<summary>Python</summary>



```python
import json
import os
import urllib.request

payload = json.loads(r'''{
  "model": "claude-haiku-4-5",
  "messages": [
    {
      "role": "user",
      "content": "Hello"
    }
  ]
}''')

request = urllib.request.Request(
    "https://gateway.respan.ai/api/v1/messages/count_tokens",
    data=json.dumps(payload).encode(),
    headers={
        "Authorization": f"Bearer {os.environ['RESPAN_API_KEY']}",
        "Content-Type": "application/json",
        "x-api-key": "YOUR_RESPAN_API_KEY",
        "anthropic-version": "2023-06-01",
    },
    method="POST",
)
with urllib.request.urlopen(request) as response:
    print(response.read().decode())
```


</details>

<details>
<summary>TypeScript</summary>



```typescript
const response = await fetch("https://gateway.respan.ai/api/v1/messages/count_tokens", {
  method: "POST",
  headers: {
    Authorization: `Bearer ${process.env.RESPAN_API_KEY}`,
    "Content-Type": "application/json",
    "x-api-key": "YOUR_RESPAN_API_KEY",
    "anthropic-version": "2023-06-01",
  },
  body: JSON.stringify({
    "model": "claude-haiku-4-5",
    "messages": [
      {
        "role": "user",
        "content": "Hello"
      }
    ]
  }),
});
if (!response.ok) throw new Error(await response.text());
console.log(await response.text());
```


</details>

## Responses

### 200

The input token count.

#### application/json


| Field | Type | Requirement | Description and constraints |
| --- | --- | --- | --- |
| `$` | `object` | Body | - |
| `input_tokens` | `integer` | Required in parent | - |


<details class="api-schema-source">
<summary>OpenAPI response schema</summary>


```json
{
  "type": "object",
  "required": [
    "input_tokens"
  ],
  "properties": {
    "input_tokens": {
      "type": "integer"
    }
  }
}
```

</details>

##### Example


```json
{
  "input_tokens": 8
}
```


### 400

Invalid request.

#### application/json


| Field | Type | Requirement | Description and constraints |
| --- | --- | --- | --- |
| `$` | `object` | Body | Reference: `#/components/schemas/GatewayAnthropicError` |
| `type` | `string` | Required in parent | Allowed: `"error"` |
| `error` | `object` | Required in parent | - |
| `error.type` | `string` | Optional | - |
| `error.message` | `string` | Optional | - |


<details class="api-schema-source">
<summary>OpenAPI response schema</summary>


```json
{
  "$ref": "#/components/schemas/GatewayAnthropicError"
}
```

</details>

### 403

The API key is missing, invalid or expired.

#### application/json


| Field | Type | Requirement | Description and constraints |
| --- | --- | --- | --- |
| `$` | `object` | Body | Reference: `#/components/schemas/GatewayAnthropicError` |
| `type` | `string` | Required in parent | Allowed: `"error"` |
| `error` | `object` | Required in parent | - |
| `error.type` | `string` | Optional | - |
| `error.message` | `string` | Optional | - |


<details class="api-schema-source">
<summary>OpenAPI response schema</summary>


```json
{
  "$ref": "#/components/schemas/GatewayAnthropicError"
}
```

</details>

##### Example


```json
{
  "type": "error",
  "error": {
    "type": "permission_error",
    "message": "Your API key is invalid or expired, please check your API key in the platform settings."
  }
}
```


## OpenAPI source

The operation and referenced components below retain the complete OpenAPI definitions, including constraints and examples.

<!-- openapi-operation:start -->
<details class="api-schema-source">
<summary>OpenAPI operation</summary>


```json
{
  "summary": "Count message tokens (Anthropic format)",
  "operationId": "countAnthropicMessageTokens",
  "tags": [
    "Gateway"
  ],
  "description": "Counts the input tokens of a Messages request without running it, as Anthropic's count tokens API does. It is served under `/api`, so set the Anthropic SDK's `base_url` to `https://gateway.respan.ai/api` for `client.messages.count_tokens()` to reach it.",
  "servers": [
    {
      "url": "https://gateway.respan.ai",
      "description": "Respan gateway"
    }
  ],
  "security": [
    {
      "RespanApiKey": []
    }
  ],
  "parameters": [
    {
      "name": "x-api-key",
      "in": "header",
      "required": false,
      "schema": {
        "type": "string"
      },
      "description": "Your Respan API key, as the Anthropic SDK sends it. `Authorization: Bearer` also works.",
      "example": "YOUR_RESPAN_API_KEY"
    },
    {
      "name": "anthropic-version",
      "in": "header",
      "required": false,
      "schema": {
        "type": "string",
        "default": "2023-06-01"
      }
    }
  ],
  "requestBody": {
    "required": true,
    "content": {
      "application/json": {
        "schema": {
          "type": "object",
          "required": [
            "model",
            "messages"
          ],
          "additionalProperties": true,
          "properties": {
            "model": {
              "type": "string"
            },
            "messages": {
              "type": "array",
              "items": {
                "type": "object",
                "additionalProperties": true
              }
            },
            "system": {
              "oneOf": [
                {
                  "type": "string"
                },
                {
                  "type": "array",
                  "items": {
                    "type": "object",
                    "additionalProperties": true
                  }
                }
              ]
            },
            "tools": {
              "type": "array",
              "items": {
                "type": "object",
                "additionalProperties": true
              }
            }
          }
        },
        "example": {
          "model": "claude-haiku-4-5",
          "messages": [
            {
              "role": "user",
              "content": "Hello"
            }
          ]
        }
      }
    }
  },
  "responses": {
    "200": {
      "description": "The input token count.",
      "content": {
        "application/json": {
          "schema": {
            "type": "object",
            "required": [
              "input_tokens"
            ],
            "properties": {
              "input_tokens": {
                "type": "integer"
              }
            }
          },
          "example": {
            "input_tokens": 8
          }
        }
      }
    },
    "400": {
      "description": "Invalid request.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/GatewayAnthropicError"
          }
        }
      }
    },
    "403": {
      "description": "The API key is missing, invalid or expired.",
      "content": {
        "application/json": {
          "schema": {
            "$ref": "#/components/schemas/GatewayAnthropicError"
          },
          "example": {
            "type": "error",
            "error": {
              "type": "permission_error",
              "message": "Your API key is invalid or expired, please check your API key in the platform settings."
            }
          }
        }
      }
    }
  },
  "x-fern-examples": [
    {
      "name": "Count tokens",
      "headers": {
        "x-api-key": "YOUR_RESPAN_API_KEY",
        "anthropic-version": "2023-06-01"
      },
      "request": {
        "model": "claude-haiku-4-5",
        "messages": [
          {
            "role": "user",
            "content": "Hello"
          }
        ]
      },
      "response": {
        "body": {
          "input_tokens": 8
        }
      }
    }
  ]
}
```

</details>
<!-- openapi-operation:end -->

<!-- openapi-path-item:start -->
<details class="api-schema-source">
<summary>OpenAPI path metadata</summary>


```json
{}
```

</details>
<!-- openapi-path-item:end -->

<!-- openapi-components:start -->
<details class="api-schema-source">
<summary>Referenced OpenAPI components</summary>


```json
{
  "schemas": {
    "GatewayAnthropicError": {
      "type": "object",
      "required": [
        "type",
        "error"
      ],
      "properties": {
        "type": {
          "type": "string",
          "enum": [
            "error"
          ]
        },
        "error": {
          "type": "object",
          "properties": {
            "type": {
              "type": "string"
            },
            "message": {
              "type": "string"
            }
          }
        }
      }
    }
  },
  "securitySchemes": {
    "RespanApiKey": {
      "type": "http",
      "scheme": "bearer",
      "bearerFormat": "Respan API key",
      "description": "Use your Respan API key for Respan API authentication. Enter only the Respan API key value; clients send Authorization: Bearer <RESPAN_API_KEY>. For /api/responses, provider credentials such as Perplexity, OpenAI, or Azure OpenAI go in Settings -> Providers or respan_params.credential_override in the request body, not in this authentication field.",
      "x-fern-bearer": {
        "name": "respanApiKey",
        "env": "RESPAN_API_KEY"
      }
    }
  }
}
```

</details>
<!-- openapi-components:end -->
