> 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.

# Create a message

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

Anthropic-compatible Messages endpoint. Accepts the Anthropic Messages request shape and routes to any catalogued model.

Also served at `/v1/anthropic/v1/messages`; both paths accept the same requests. This bare path is what the Anthropic SDK builds from a bare-host base URL, so pointing the SDK at `https://api-gateway.merge.dev` works with no other changes.

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

## Authentication

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

## Request

### Body (application/json)

This endpoint expects an AnthropicMessageRequest.

- `model` (string, required)
- `max_tokens` (integer, required)
- `messages` (list of AnthropicMessageParam, required)
- `system` (AnthropicMessageRequestSystem, optional, nullable)
- `stream` (boolean, optional, default: false)
- `temperature` (double, optional, nullable)
- `top_p` (double, optional, nullable)
- `top_k` (integer, optional, nullable)
- `stop_sequences` (list of string, optional, nullable)
- `tools` (list of AnthropicToolDef, optional, nullable)
- `tool_choice` (map from string to any, optional, nullable)
- `metadata` (map from string to any, optional, nullable)
- `service_tier` (string, optional, nullable)
- `cache_control` (map from string to any, optional, nullable) — Top-level prompt-caching setting.
- `thinking` (AnthropicThinkingConfig, optional, nullable) — Extended thinking settings for models that support it.
- `output_config` (AnthropicOutputConfig, optional, nullable) — Anthropic output settings; only `effort` is applied.
- `customer` (string, optional, nullable) — Customer ID (UUID) to scope this request to, applying that customer's routing policy, provider keys, budget, and usage attribution.
- `routing_policy_id` (string, optional, nullable) — Routing policy ID for this request: an org-level policy, or a project or customer policy when the request carries that scope.
- `priority_order` (list of AnthropicMessageRequestPriorityOrderItems, optional, nullable) — Ordered list of models to try, first success wins, with the same rules as `priority_order` on `POST /v1/responses`.
- `vendor` (string, optional, nullable) — Restrict routing to one vendor (hosting platform).
- `vendors` (list of string, optional, nullable) — Ordered list of acceptable vendors; the first available one wins.
- `provider_options` (map from string to any, optional, nullable) — Provider-specific options, keyed by provider family.
- `include_routing_metadata` (boolean, optional, default: false) — Return routing metadata for this request.
- `include_guardrails_metadata` (boolean, optional, default: false) — Return prompt-injection and DLP results in a top-level `guardrails` object.
- `service_tier_fallback` (boolean, optional, default: false) — Retry once at the standard tier, billed at standard rates, if the requested tier is throttled (429 or 503).

## Response

### 200

Successful Response

- `id` (string, required)
- `type` ("message", required)
- `role` ("assistant", required)
- `model` (string, required)
- `content` (list of AnthropicContentBlock, required)
- `usage` (AnthropicUsage, required)
- `stop_reason` (enum, optional, nullable)
  - Allowed values: `end_turn`, `max_tokens`, `stop_sequence`, `tool_use`
- `stop_sequence` (string, optional, nullable)

## Errors

### 422 Unprocessable Entity Error

Validation Error

- `detail` (list of ValidationError, optional)

## Types

### AnthropicMessageParam

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

### AnthropicMessageRequestSystem

### 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)

### AnthropicOutputConfig

Anthropic `output_config` block; only `effort` is applied.

- `effort` (string, optional, nullable) — Reasoning effort.

### AnthropicMessageRequestPriorityOrderItems

### 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.

### AnthropicUsage

- `input_tokens` (integer, required)
- `output_tokens` (integer, required)
- `cache_creation_input_tokens` (integer, optional, nullable)
- `cache_read_input_tokens` (integer, 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

### PriorityOrderEntry

One entry of `priority_order`: a model, optionally pinned to vendors.

- `model` (string, required) — Model id, `provider/model` or a bare base name that resolves the same way `model` does.
- `priority` (integer, optional, nullable) — Lower tries first, as in the routing policies API's PRIORITY shape. Omit to use list order; explicit values sort ahead of list order.
- `vendors` (list of string, optional, nullable) — Pin this entry to these execution hosts, in order of preference. Omit to allow every vendor that serves the model. Must not be empty when sent.

### AnthropicContentBlockContent

### ValidationErrorLocItems

### ValidationErrorCtx

## Examples

**Request**

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

**Response**

```json
{
  "id": "msg_a1b2c3d4e5f6",
  "type": "message",
  "role": "assistant",
  "model": "anthropic/claude-sonnet-5",
  "content": [
    {
      "type": "text",
      "text": "The capital of France is Paris."
    }
  ],
  "usage": {
    "input_tokens": 14,
    "output_tokens": 8
  },
  "stop_reason": "end_turn",
  "stop_sequence": null
}
```

**SDK Code**

```python
import requests

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

payload = {
    "model": "anthropic/claude-sonnet-5",
    "max_tokens": 1024,
    "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';
const options = {
  method: 'POST',
  headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
  body: '{"model":"anthropic/claude-sonnet-5","max_tokens":1024,"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"

	payload := strings.NewReader("{\n  \"model\": \"anthropic/claude-sonnet-5\",\n  \"max_tokens\": 1024,\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")

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  \"max_tokens\": 1024,\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")
  .header("Authorization", "Bearer <token>")
  .header("Content-Type", "application/json")
  .body("{\n  \"model\": \"anthropic/claude-sonnet-5\",\n  \"max_tokens\": 1024,\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', [
  'body' => '{
  "model": "anthropic/claude-sonnet-5",
  "max_tokens": 1024,
  "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");
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  \"max_tokens\": 1024,\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",
  "max_tokens": 1024,
  "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")! 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()
```