Claude Sonnet 4.6 API Key Setup: Endpoint, Model ID, and Python Example

Set up a Claude Sonnet 4.6 API key with OurToken's Messages API endpoint. Copy the exact model ID, test a cURL request, and call Claude Sonnet 4.6 from Python.

O
OurToken Team//16 min
Claude Sonnet 4.6 API Key Setup: Endpoint, Model ID, and Python Example

A Claude Sonnet 4.6 API key is only useful when the credential, base URL, endpoint, model ID, and request body agree. A valid key can still return a 400, 401, or 404 if an application sends it to the wrong operation path, uses claude-sonnet-4.6 instead of claude-sonnet-4-6, or points the OpenAI Python SDK at a route that expects the Anthropic Messages API shape.

The important difference for Claude on OurToken is the route. The GLM, Kimi, and DeepSeek setup guides use the OpenAI-compatible /chat/completions path. The current OurToken Claude Sonnet 4.6 model page recommends the Anthropic-native Messages API instead. That changes the endpoint, the authentication header, the request body, and the response shape. This guide follows that recommended path: create or locate an API key, configure the Claude Sonnet 4.6 API endpoint, run a cURL smoke test, call the same route from Python, inspect usage fields, estimate cost, and add production safeguards. The current route is:

Base URL:     https://api.ourtoken.ai/v1
Full URL:     https://api.ourtoken.ai/v1/messages
Model ID:     claude-sonnet-4-6

The examples use the current Claude Sonnet 4.6 API page as the configuration source, and follow the public Anthropic Messages API reference for request and response shapes. The model page is the compatibility boundary for the OurToken route: use its model ID, request fields, and current prices rather than assuming that every Anthropic parameter is accepted unchanged.

Verification status: The route, model ID, and request/response shapes follow the OurToken model page's recommended Messages API path and the public Anthropic Messages API specification. The examples were not executed with a live API key in this draft. Confirm the exact header convention, usage field names, and current pricing on the live OurToken page before sending production traffic.

Claude Sonnet 4.6 API Key Setup and First Request

The key, base URL, operation path, and model value are separate settings. Keep them separate in environment variables or server-side configuration so a model switch does not require editing every request call.

Exact values to copy

SettingCurrent OurToken valueWhat it controls
API keyOURTOKEN_API_KEYAuthenticates the request
SDK base URLhttps://api.ourtoken.ai/v1The URL passed to a Bearer-auth HTTP client or SDK
Full API endpointhttps://api.ourtoken.ai/v1/messagesThe URL used by cURL or raw HTTP
Model IDclaude-sonnet-4-6Selects the Claude Sonnet 4.6 route
Auth headerAuthorization: Bearer YOUR_API_KEYBearer-token authentication, same as other OurToken routes
Required body fieldsmodel, messages, max_tokensIdentifies the route, conversation, and output cap

The difference between a base URL and a full endpoint is the most common setup mistake. cURL does not construct any path; it must use the complete /v1/messages URL. The second common mistake is reaching for the OpenAI SDK: this route does not return a choices array, so client.chat.completions.create will not parse the response even if the request reaches the server. A third mistake is sending the Anthropic-native x-api-key header: the OurToken route authenticates with Authorization: Bearer, so an x-api-key-only request returns 401.

What the Messages API route means

The OurToken Claude route uses the Anthropic Messages API shape — the /messages path, the messages array, a top-level system field, and the content block response — but it authenticates with the same Authorization: Bearer header as every other OurToken route. It does not use the Anthropic-native x-api-key or anthropic-version headers. The model-specific value is claude-sonnet-4-6.

Do not use any of these as the API model value:

  • claude-sonnet-4.6, which uses a dot instead of a hyphen;
  • claude-4-6-sonnet, which reorders the name;
  • anthropic/claude-sonnet-4-6, which resembles a website catalog path;
  • Claude Sonnet 4.6, which is a display name rather than the current model ID.

The Messages API shape differs from Chat Completions in four places that break a naive port:

  1. system is a top-level parameter, not a message with role: "system".
  2. max_tokens is required on every request, not optional.
  3. The response content is an array of typed blocks, not a single string.
  4. Usage is reported as input_tokens and output_tokens, not prompt_tokens and completion_tokens.

The current OurToken page lists optional fields such as temperature, top_p, tools, tool_choice, and stop_sequences. Start without them. Add one at a time after the plain request works, because a route can accept a generic field while still applying model-specific limits or behavior. If your application depends on the OpenAI Chat Completions shape, check the model page for whether OurToken also exposes a /chat/completions route for Claude before assuming it; this guide uses the recommended /v1/messages path.

Get and Test a Claude Sonnet 4.6 API Key

An API key authenticates an application request. It is not an Anthropic Console login, a model ID, or a browser session. For the OurToken route, use the OurToken API Keys page to create or manage the credential. The protected page may redirect to login before key management is available.

Store the key in a server-side secret or a local environment variable during development. Never put it in frontend JavaScript, a mobile bundle, a public repository, a notebook shared with other people, or a screenshot.

On macOS or Linux:

export OURTOKEN_API_KEY="paste-your-key-locally"

On Windows PowerShell:

$env:OURTOKEN_API_KEY = "paste-your-key-locally"

The variable name is an application convention. The HTTP header on this route is the standard OurToken Bearer token:

Authorization: Bearer YOUR_API_KEY

Do not send the Anthropic-native x-api-key or anthropic-version headers. The OurToken route authenticates with Authorization: Bearer even though the request and response body follow the Anthropic Messages API shape.

Configuration checklist.

  1. The key was created for the OurToken gateway.
  2. The full cURL URL ends in /v1/messages, not /v1/chat/completions.
  3. The Anthropic Python SDK base URL ends in /v1, not /messages.
  4. The JSON model value is exactly claude-sonnet-4-6.
  5. The request includes max_tokens.
  6. The system instruction, if any, is a top-level field, not a message.
  7. The key is available only to the server process that needs it.

cURL smoke test

This is a minimal non-streaming Claude Sonnet 4.6 cURL example against the Messages API. It uses a short prompt and a small output cap so configuration failures return quickly:

curl -sS https://api.ourtoken.ai/v1/messages \
  -H "content-type: application/json" \
  -H "Authorization: Bearer ${OURTOKEN_API_KEY}" \
  -d '{
    "model": "claude-sonnet-4-6",
    "max_tokens": 256,
    "messages": [
      {
        "role": "user",
        "content": "Give me a three-step checklist for reviewing a database migration."
      }
    ]
  }'

PowerShell version.

PowerShell can build the JSON body as an object. This avoids nested quote escaping and is easier to edit for a real prompt:

$payload = @{
  model = "claude-sonnet-4-6"
  max_tokens = 256
  messages = @(
    @{
      role = "user"
      content = "Give me a three-step checklist for reviewing a database migration."
    }
  )
} | ConvertTo-Json -Depth 5

curl.exe "https://api.ourtoken.ai/v1/messages" `
  -H "content-type: application/json" `
  -H "Authorization: Bearer $env:OURTOKEN_API_KEY" `
  --data-raw $payload

What a successful response should contain.

Do not depend on the exact generated wording. Inspect the response structure and confirm the returned model before adding application logic. The Messages API returns a content array of typed blocks, not a choices array:

{
  "id": "msg_redacted",
  "type": "message",
  "role": "assistant",
  "model": "claude-sonnet-4-6",
  "content": [
    {
      "type": "text",
      "text": "1. Review the schema changes.\n2. Test rollback.\n3. Validate production impact."
    }
  ],
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 30,
    "output_tokens": 24
  }
}

This is an illustrative response shape, not a live response captured from an OurToken account. The current model page documents input_tokens and output_tokens for the Messages API route. Read the assistant text from content[0].text, not from choices[0].message.content. When cache details are present, the usage object reports cached tokens separately from input_tokens (see the cost section below).

Common cURL mistakes.

SymptomLikely causeFix
401 UnauthorizedMissing key, or x-api-key sent instead of BearerUse the Authorization: Bearer header with an OurToken key
404 Not FoundWrong path or model valueUse /v1/messages and claude-sonnet-4-6
400 for a missing fieldmax_tokens omitted, or system placed inside messagesAdd max_tokens and move system to the top level
400 after adding an optionThe route rejects an optional fieldRemove it and compare with the current model page
429 Too Many RequestsRate limit or account capacityUse bounded backoff and avoid unlimited retries
529 OverloadedUpstream capacity pressureBounded retry with jitter, or shed load
Empty or partial outputOutput cap or context limit was reachedInspect stop_reason and adjust the prompt or max_tokens

Do not retry a 400, 401, or 404 request unchanged. Those responses indicate a configuration or request problem, not a transient service failure.

Claude Sonnet 4.6 Python API Usage

The Anthropic Messages API body shape pairs with OurToken's standard Authorization: Bearer authentication. The official anthropic SDK sends the Anthropic-native x-api-key and anthropic-version headers by default, which the OurToken route may reject; it is safer to call the endpoint with a Bearer-auth HTTP client such as httpx so the auth header matches the model page. Install httpx in the same environment that will run the integration:

python -m pip install --upgrade httpx

SDK note: If you prefer the anthropic SDK, verify with a live key whether OurToken accepts its default x-api-key header on this route. The example below uses httpx because it sends exactly the Authorization: Bearer header documented on the model page.

Build the request against the base URL plus the /messages path, and pass the Bearer header explicitly:

import os

import httpx


BASE_URL = "https://api.ourtoken.ai/v1"
HEADERS = {
    "content-type": "application/json",
    "Authorization": f"Bearer {os.environ['OURTOKEN_API_KEY']}",
}

response = httpx.post(
    f"{BASE_URL}/messages",
    headers=HEADERS,
    json={
        "model": "claude-sonnet-4-6",
        "max_tokens": 256,
        "system": "You are a concise software engineering assistant.",
        "messages": [
            {
                "role": "user",
                "content": "List the checks for a safe database migration.",
            }
        ],
    },
    timeout=60.0,
)
response.raise_for_status()
data = response.json()

# Messages API: content is an array of typed blocks, not a choices array.
print(data["content"][0]["text"])

usage = data["usage"]
print(
    {
        "input_tokens": usage["input_tokens"],
        "output_tokens": usage["output_tokens"],
    }
)

The response access pattern matters. Read the assistant text from data["content"][0]["text"], not from a choices array. Because the example uses httpx, the Authorization: Bearer header is set explicitly and matches the model page; no SDK-specific auth header is sent.

Keep the first Python request deterministic.

The first successful call should prove four things: the key is accepted, the route is reachable, the model ID is correct, and the response contains an assistant text block. These checks catch proxy or configuration mistakes earlier than a long application workflow:

assert data["model"] == "claude-sonnet-4-6"
assert data["content"]
assert data["content"][0]["type"] == "text"
assert data["stop_reason"] in ("end_turn", "max_tokens", "stop_sequence")

In production, replace assertions with structured error handling and telemetry. An application should fail clearly if a gateway returns a different model or an empty response.

Multi-turn, streaming, and optional fields

The Messages API is stateless from the application's perspective. Send the conversation history again when asking a follow-up question. Reuse the full assistant content (the list of content blocks), not just the text string, so tool_use blocks and any extension fields are carried into the next request intact:

def call(messages, max_tokens=256):
    r = httpx.post(
        f"{BASE_URL}/messages",
        headers=HEADERS,
        json={
            "model": "claude-sonnet-4-6",
            "max_tokens": max_tokens,
            "system": "You are a concise software engineering assistant.",
            "messages": messages,
        },
        timeout=60.0,
    )
    r.raise_for_status()
    return r.json()


messages = [
    {"role": "user", "content": "What should I verify before a migration?"},
]

first = call(messages)

# Preserve the full assistant content (a list of typed blocks), not just the
# text, so tool_use blocks and any extensions carry into the next turn.
messages.append({"role": "assistant", "content": first["content"]})
messages.append({"role": "user", "content": "Now turn that into a release checklist."})

second = call(messages)
print(second["content"][0]["text"])

Do not replace the assistant turn with {"role": "assistant", "content": first["content"][0]["text"]}. That drops any tool_use block and breaks a tool-using loop on the next turn.

When tools are involved, preserve tool-use IDs too. In the Messages API, the assistant turn returns a tool_use block with an id, and each following tool result is a tool_result block whose tool_use_id matches that call. Never invent or reorder those IDs:

# After an assistant turn that requested a tool:
# first["content"] includes
#   {"type": "tool_use", "id": "toolu_1", "name": "run_tests", "input": {...}}

tool_result = run_tests()  # your own function

messages.append(
    {
        "role": "user",
        "content": [
            {
                "type": "tool_result",
                "tool_use_id": "toolu_1",
                "content": str(tool_result),
            }
        ],
    }
)

The tool-calling guide covers general tool-call validation concerns on OurToken; for the Claude-native tool-use block format, follow the Anthropic Messages API reference above.

For streaming output, set "stream": true in the request body and read the Server-Sent Events stream with httpx, printing text deltas from content_block_delta events:

with httpx.stream(
    "POST",
    f"{BASE_URL}/messages",
    headers=HEADERS,
    json={
        "model": "claude-sonnet-4-6",
        "max_tokens": 256,
        "stream": True,
        "messages": [{"role": "user", "content": "Summarize the deployment checklist."}],
    },
    timeout=60.0,
) as resp:
    resp.raise_for_status()
    for line in resp.iter_lines():
        if not line or not line.startswith("data: "):
            continue
        import json
        event = json.loads(line[len("data: "):])
        if event.get("type") == "content_block_delta":
            delta = event.get("delta", {})
            if delta.get("type") == "text_delta":
                print(delta.get("text", ""), end="", flush=True)
print()

Streaming changes where you receive the final usage object. In a streamed response, the final message_delta event carries the usage; individual content_block_delta events do not. Parse the event stream end-to-end rather than assuming every chunk contains complete usage data. Confirm the current stream behavior on the model page before relying on it.

Do not add tools, structured output, or provider-specific controls to the first request. Verify each optional field on the current OurToken route, then add one feature and one test case at a time.

Move from Testing to Production

A successful smoke test proves only that one request passed. A usable Claude Sonnet 4.6 integration also needs secret isolation, usage accounting, budget controls, timeouts, retries, and a plan for model selection.

Request architecture.

User or internal service
          |
          | application request
          v
Your backend or job worker
          |
          | Authorization: Bearer OURTOKEN_API_KEY
          v
https://api.ourtoken.ai/v1/messages
          |
          | model = claude-sonnet-4-6
          v
Claude Sonnet 4.6 route
          |
          v
Assistant content blocks + usage data
          |
          v
Redacted logs, budget checks, and application output

Never expose the API key to a browser. The backend should also own the model allowlist instead of accepting an arbitrary model string from an untrusted client:

SUPPORTED_MODELS = {
    "sonnet": "claude-sonnet-4-6",
}


def resolve_model(name: str) -> str:
    try:
        return SUPPORTED_MODELS[name]
    except KeyError as exc:
        raise ValueError("Unsupported model selection") from exc

A practical coding workflow.

The current Claude Sonnet 4.6 model page positions the route for coding workflows, long-context evaluation, and production assistant tasks, with a 200K-token context window. That window fits a large diff plus test output in one request; the cost of that long prefix is where the cached-input price in the next section pays off. A code-review service can start with a stable system instruction, the relevant diff, and test output, then ask for findings in a predictable format. A safe workflow is:

  1. Keep repository instructions and the review policy on the server.
  2. Send only the relevant diff and test output for each review.
  3. Bound max_tokens so a malformed prompt cannot create an unbounded bill.
  4. Validate paths, commands, and structured fields before using model output.
  5. Require human approval before a tool can modify a repository.
  6. Record model, status, latency, token usage, and cost without logging the key.

For a service with several supported models, the model routing guide describes how to send simpler work to a lower-cost route and reserve stronger routes for tasks that need them. If you are moving from the OpenAI Chat Completions shape to the Anthropic Messages API shape, the Responses API migration guide walks through the request and response differences and a rollback plan.

Cost, usage, and reliability

The following prices are the current OurToken Claude Sonnet 4.6 listing checked on July 24, 2026. The Official column is Anthropic's first-party list price shown for comparison on the OurToken model page; OurToken lists the route at roughly 40% of that reference price. Prices can change, so confirm the live Claude Sonnet 4.6 pricing and model configuration before setting a budget.

Token categoryOfficial (Anthropic)OurToken price
Input$3.00 / 1M tokens$1.20 / 1M tokens
Output$15.00 / 1M tokens$6.00 / 1M tokens
Cached input$0.30 / 1M tokens$0.12 / 1M tokens
Cache writes$3.75 / 1M tokens$1.50 / 1M tokens

For 100,000 uncached input tokens and 10,000 output tokens:

Input:   100,000 / 1,000,000 * $1.20 = $0.12000
Output:   10,000 / 1,000,000 * $6.00 = $0.06000
Total:                                 = $0.18000

The Messages API usage object is structured differently from OpenAI Chat Completions, and the difference matters for cost math. In the Anthropic Messages API, input_tokens is the uncached input count; cached tokens are reported in separate fields. You do not need to subtract cached tokens from input_tokens the way you subtract cached_tokens from prompt_tokens on an OpenAI-compatible route:

estimated_cost =
  input_tokens * input_rate
  + cache_read_input_tokens * cache_read_rate
  + cache_creation_input_tokens * cache_write_rate
  + output_tokens * output_rate

If the route returns cache_read_input_tokens or cache_creation_input_tokens, use them at their own rates and do not also charge those tokens at the full input_rate. Caching does not reduce the number of tokens your application sends; it changes how a portion of input is billed. The prompt caching guide explains how stable prefixes, cache hits, and usage measurement affect a compatible API workflow. Measure actual usage instead of assuming that every repeated prompt receives a cache hit.

Retry and timeout policy.

StatusRetry by default?Action
400NoFix the body, add max_tokens, or remove an unsupported field
401NoReplace or reconfigure the credential; check the header type
404NoCheck the base URL, path, and model ID
429Yes, boundedBack off and respect account limits
529Yes, boundedBack off with jitter; the upstream is overloaded
500-599Yes, boundedRetry with a maximum attempt count
Network timeoutConditionalRetry only when duplicate execution is safe

Retries can duplicate a model request after a client-side timeout. For chat-only work, that may be acceptable; for tool calls or external side effects, use an idempotency strategy and require confirmation before executing the action.

Release checklist.

  1. The key is available only to a server process or protected worker.
  2. The cURL smoke test succeeds with model: "claude-sonnet-4-6" against /v1/messages.
  3. The Anthropic Python client uses base_url="https://api.ourtoken.ai/v1".
  4. The response model, content block type, stop reason, and usage are validated.
  5. Cached and cache-creation tokens are billed at their own rates, not double-counted at input_rate.
  6. 400, 401, 404, 429, 529, timeout, and 5xx behavior is tested.
  7. Prompts, responses, and the Authorization header are redacted in logs.
  8. Tools, streaming, and structured output are enabled one at a time.

Conclusion and Frequently Asked Questions

The reliable Claude Sonnet 4.6 setup is small: create an OurToken key, set https://api.ourtoken.ai/v1 as the base URL, call /v1/messages with the Authorization: Bearer header, and send the exact claude-sonnet-4-6 model ID. Start with the short cURL request, repeat it in Python with a Bearer-auth HTTP client such as httpx, inspect usage, and only then add streaming, tools, structured output, or larger prompts.

When you are ready to test with a real credential, review the Claude Sonnet 4.6 API configuration and create a key through the OurToken API Keys page. Keep the key server-side and compare actual usage with the dated pricing on the live page before moving to production traffic.

FAQ

What is the Claude Sonnet 4.6 API endpoint on OurToken?

The current full endpoint is https://api.ourtoken.ai/v1/messages (the Anthropic Messages API). When using the Anthropic Python SDK, set base_url to https://api.ourtoken.ai/v1 and call client.messages.create. Do not use /v1/chat/completions for Claude unless the model page documents that route.

What is the Claude Sonnet 4.6 model ID?

Use claude-sonnet-4-6 as the API model value. Do not use claude-sonnet-4.6, claude-4-6-sonnet, the catalog path anthropic/claude-sonnet-4-6, or the display name Claude Sonnet 4.6.

Can I use the OpenAI Python SDK for Claude Sonnet 4.6?

No. The recommended OurToken route for Claude is the Anthropic Messages API, which returns a content array rather than a choices array. Use the official anthropic Python SDK with the OurToken base URL. If your application must use the OpenAI SDK, first confirm on the model page whether OurToken exposes a /chat/completions route for Claude.

Can I use an Anthropic Console key with OurToken?

Use an OurToken API key with api.ourtoken.ai. API keys belong to the gateway that issued them; an Anthropic Console key is not automatically valid on the OurToken route.

Which usage fields should I read in Python?

Use usage.input_tokens and usage.output_tokens. If caching is active, also read usage.cache_read_input_tokens and usage.cache_creation_input_tokens. These are separate from input_tokens, so do not subtract cached tokens from input_tokens the way you would on an OpenAI-compatible route.

Is max_tokens required?

Yes. The Messages API requires max_tokens on every request, unlike OpenAI Chat Completions where it is optional. A request without it returns a 400.