The hard part of getting started with the Claude API is not sending an HTTP request. It is the small details that trip people up: which header carries the key, whether anthropic-version is required, why max_tokens cannot be omitted, and why content is an array instead of a string. Get these right, and a minimal call takes about ten minutes to work.
This article follows the order of account and key, request headers, curl, Python, streaming and parameters, error troubleshooting, and key security, then explains how to use a compatible gateway as an alternative entry point. Model IDs, context, and billing follow Anthropic's official documentation and the on-site model pricing page.
Note: Anthropic and Claude are trademarks of their respective owners, as is OpenAI. This article is technical integration guidance only. Models, prices, and quotas change; verify against official documentation before connecting.
1. Before you start: account, workspace, and key
The Claude API uses the Anthropic Console to manage accounts, workspaces, API keys, and billing. Confirm three things before starting:
| Item | What to confirm | Notes |
|---|---|---|
| Account | Email verifiable, can sign in to Console | Company email is recommended for teams |
| Workspace | Which workspace the key belongs to | Workspace affects members, keys, and usage attribution |
| Billing | Payment method, billing details, available quota | Follow what the Console actually shows |
If your team has not decided who manages billing, do not rush to create a production key. Once a key is issued, usage and permissions attach to the corresponding workspace, and splitting later costs more.
2. Create an API key in six steps
- Open the Anthropic Console (console.anthropic.com), register or sign in, and verify your email.
- Create or select a workspace. Keep production, testing, and personal experiments separate so one key is not used everywhere.
- Go to the API Keys page, create a new key, and name it clearly, for example
prod-backend-2026-10. - Copy the key and immediately store it in a secrets manager or environment variable. Most consoles show the full value only at creation.
- Confirm the payment method, billing details, and quota settings on the Console billing page. Whether prepayment, invoices, and spending caps are available depends on the options actually offered.
- Set the environment variable locally and send a minimal request to verify the key works.
export ANTHROPIC_API_KEY="sk-ant-your-key"
Do not put keys in code, Git repositories, frontend pages, or chat logs. Create a separate key for testing as well, so it can be revoked at any time.
3. Request headers and a minimal curl call
The Messages API endpoint is POST https://api.anthropic.com/v1/messages. Three headers matter most:
| Header | Value | Purpose |
|---|---|---|
x-api-key |
Your API key | Anthropic API key authentication |
anthropic-version |
2023-06-01 |
Specifies the API version; missing values may cause errors |
content-type |
application/json |
Declares a JSON request body |
Note: the API key goes in x-api-key, not Authorization: Bearer. Mixing these two authentication styles is a common source of 401.
curl https://api.anthropic.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-opus-5-5",
"max_tokens": 1024,
"system": "You are a concise technical assistant.",
"messages": [
{"role": "user", "content": "Explain what an API gateway is in three sentences."}
]
}'
The model ID in the example is only one currently available option; actual models, context, and prices follow the official Models API and the on-site model pricing. The content field in the response is an array of content blocks, and text is usually in content[0].text, but the safer approach is to iterate and check for type == "text".
4. Call the Messages API from Python
Install the official SDK:
pip install anthropic
A minimal call:
import os
import anthropic
client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
resp = client.messages.create(
model="claude-opus-5-5",
max_tokens=1024,
system="You are a concise technical assistant.",
messages=[
{"role": "user", "content": "Explain what an API gateway is in three sentences."}
],
)
for block in resp.content:
if block.type == "text":
print(block.text)
print(resp.stop_reason)
print(resp.usage.input_tokens, resp.usage.output_tokens)
A few points:
systemis a top-level parameter; do not write it as a{"role": "system"}message. Messages API roles are mainlyuserandassistant.max_tokensis required and sets the maximum output length for this reply. Too small truncates the answer andstop_reasonshowsmax_tokens; too large requires considering cost and timeouts.resp.contentis a block array that may contain text blocks, thinking blocks, or tool-use blocks. Business code should not assume text only.- Record
usageandstop_reason; reconciliation and troubleshooting depend on them.
5. system, max_tokens, and streaming
system holds role definitions, output format, and boundary conditions. Put stable content first and variable user input in messages to improve cache hits.
max_tokens is not "the more the better." It caps the output per call and does not change input cost; long reports and long code need enough room, while classification and extraction can use smaller values. In production, configure it per endpoint type rather than using one global value.
Streaming suits long answers and interactive interfaces. With the Python SDK:
with client.messages.stream(
model="claude-opus-5-5",
max_tokens=4096,
system="You are a technical assistant.",
messages=[{"role": "user", "content": "Write a 200-word product description."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
Streaming requests also return usage and stop_reason; do not omit them when storing results. With raw HTTP, add "stream": true to the request body; the response is an SSE event stream, parsed by events such as content_block_delta.
6. Model naming and version selection
Claude models are divided into families such as Opus, Sonnet, and Haiku, with different positioning, context, and pricing. Model IDs commonly come in two forms: stable aliases and dated snapshots. Decide explicitly which one production uses, and do not paste the console display name into code.
Suggested selection order:
- Use a business evaluation set to shortlist families that meet quality requirements.
- Compare latency, context, and cost.
- Confirm the model is available in the target region and access method.
Models are added and retired, and old IDs may enter legacy status. Centralize model names in configuration or a mapping table so migration changes one place. Available models follow the official Models API, the Console, and the on-site model pricing.
7. Troubleshooting 401, 429, and 400
| Status | Common cause | Order of handling |
|---|---|---|
| 401 | Missing key, wrong header, revoked key, workspace mismatch | Check x-api-key, spaces and line breaks, key status, base URL |
| 429 | Request rate or token rate exceeded, concurrency spike, quota issue | Read retry-after, exponential backoff with jitter, split keys, reduce concurrency |
| 400 | Invalid JSON, missing max_tokens, wrong model ID, parameter out of range |
Keep the error body and request ID, check the request body item by item |
| 404 | Nonexistent path or model name | Confirm /v1/messages and the model ID |
| 5xx | Temporary upstream failure | Retry a limited number of times, then switch to a backup endpoint |
When troubleshooting, keep the request-id response header first. For 401, do not suspect balance; check the authentication header and the key itself. A 429 does not necessarily mean "out of money"; it may be a rate limit. A 400 is usually a request-body problem, and the error message often names the specific field.
8. Key security and a compatible gateway alternative
At minimum, do four things for key security: store keys only in environment variables or a secrets manager; split keys by project; set usage alerts; rotate regularly and revoke keys for departing members. Long-lived keys must never appear in frontends, mobile apps, or public repositories.
Teams facing network, payment, or invoicing issues can use a gateway that provides an Anthropic-compatible endpoint instead of the official address. With the official SDK, usually only base_url and the key change:
import os
from anthropic import Anthropic
client = Anthropic(
api_key=os.environ["ZSQH_API_KEY"],
base_url="https://ai.zhongshangqihang.com",
)
resp = client.messages.create(
model="use-the-model-name-from-the-site-list",
max_tokens=256,
messages=[{"role": "user", "content": "Reply with OK only"}],
)
print(resp.content)
If the gateway only provides an OpenAI-compatible interface, you need to change the request structure or add an adaptation layer; changing only the base URL is not enough. When choosing a gateway, confirm three things: whether it supports the native Anthropic protocol, how model names map, and whether rate-limit and logging policies are transparent.
FAQ
Is the Claude API the same as a Claude web subscription?
No. The web product is a user-facing subscription, while the API is billed by usage; account systems, quotas, and management entry points differ. API keys, billing, and usage are managed in the Anthropic Console.
Can I see the full API key after creating it?
In most cases it is shown only once at creation. Afterward you can see only the prefix or name, so store it in a secrets manager immediately. If lost, revoke the old key and create a new one.
Why is max_tokens required?
The Messages API requires an explicit output cap to control generation length and resources. Omitting it returns 400. Set a reasonable value for the task rather than maxing it out blindly.
Is a 429 an exhausted quota or excessive concurrency?
Both are possible. Check the response body and retry-after: short bursts usually indicate rate or concurrency problems, while sustained occurrences with abnormal billing suggest plan or usage issues. Remedies include backoff, lower concurrency, and splitting keys.
Do teams in China need a gateway?
Not necessarily. Teams that can connect reliably and complete payment and compliance reviews are simpler with direct official access. Evaluate a gateway when you need RMB settlement, invoices, a unified multi-model entry point, or network optimization, and confirm its data and incident-handling policies.
Next steps
Register for ZSQH AI Gateway, run the minimal /v1/messages request with a test key, then connect your business. Models, context, and billing follow model pricing.
Related reading:
