59API

← Retour aux guides

Claude Messages API: Advanced Calling Patterns

API · EN · 2026-09-09

Call Claude Messages with a Production-Ready Request

The Claude Messages API accepts a POST request at https://api.59api.com/v1/messages when using 59API as a Claude-compatible relay. Send your 59API key in the x-api-key header, set anthropic-version to 2023-06-01, include content-type: application/json, and provide a JSON body containing model, max_tokens, and messages. A minimal request uses a user message such as {"role":"user","content":"Summarize this release note in three bullets."}. Keep system instructions in the top-level system field rather than placing them in a user message; this gives the model a cleaner instruction hierarchy and makes requests easier to audit.

Always set max_tokens deliberately. It is an output cap, not a target length, so an unnecessarily high value can make cost and latency less predictable. For extraction, classification, and compact structured responses, begin with 300 to 800 tokens. Reserve larger limits for code generation, multi-step analysis, or long editorial output. 59API is useful here because it provides pay-as-you-go access to native official-quality Claude models, including Opus, Sonnet, Haiku, and Fable, without forcing a model downgrade. Confirm the exact model identifiers enabled for your account before hard-coding them into production.

Build Messages That Preserve Context Without Wasting Tokens

The messages array is a conversation transcript. Each item must use a supported role, normally user or assistant. Do not resend loosely summarized history when exact prior decisions, tool outputs, or constraints matter. Instead, retain the relevant turns and remove stale discussion. For long-running sessions, maintain a server-side conversation record, select the turns needed for the next decision, and add a compact application-generated summary only after verifying that it does not replace important facts.

Use content blocks when a request mixes text, images, cached instructions, or tool results. This is more reliable than asking the model to infer data boundaries from one large string. Place stable, lengthy instructions or reference material near the beginning of the request and use Claude prompt caching where the selected model and account support it. A cacheable block can reduce repeated input processing for workloads such as document assistants, repository analysis, and repeated policy checks. Measure cache read and write usage in returned usage fields rather than assuming every request is cached.

Stream Safely and Handle Completion States

Set stream to true when the interface benefits from incremental text. The response is delivered as server-sent events, so your client must parse event boundaries and concatenate text deltas in order. Render only recognized text deltas to the user; retain the complete final message on the server for logging and downstream processing. Do not treat the first streamed text as a completed answer. Wait for the final message event to obtain final usage, stop_reason, and any tool-use blocks.

Inspect stop_reason on every completed response. An end_turn result generally means Claude finished normally. max_tokens means the answer was cut off and your application should either request a continuation with the prior transcript or present a clear incomplete state. A tool_use result means the model is requesting an application action, not delivering a final answer. Design this branch explicitly instead of hoping a text parser can handle all responses.

Implement Tool Use as a Deterministic Loop

Define each tool with a precise name, description, and JSON input schema. Descriptions should say what the tool can do, required permissions, and meaningful limits. When Claude returns a tool_use content block, execute only an allowlisted tool, validate the input against your schema, enforce authorization on the server, and record the result. Then append Claude's assistant message unchanged to the transcript and send a new user message containing a tool_result block tied to the returned tool_use_id. This preserves the protocol and lets Claude reason from the actual result.

Never let a model-generated tool argument directly control shell commands, database writes, payment actions, or external requests. Add parameter validation, scoped credentials, timeouts, and human confirmation for consequential operations. For read-heavy integrations, a narrow tool such as get_order_status is safer and easier to evaluate than a general database-query tool.

Control Failures, Costs, and Model Selection

Classify errors before retrying. A 400 response usually indicates an invalid payload and needs a code fix. A 401 or 403 response requires key, account, or permission checks. For 429 rate limits and temporary 5xx or overload responses, use exponential backoff with jitter and honor Retry-After when supplied. Limit retry attempts and make side-effecting tool operations idempotent so a network retry cannot duplicate work.

Route by task complexity: use Haiku for high-volume fast classification, Sonnet for most coding and reasoning workflows, and Opus for difficult analysis where quality justifies the extra spend. Track quality and cost by task type rather than choosing one model globally. 59API's low-cost relay pricing and referral rebate make this model-routing strategy practical for teams that need Claude compatibility alongside GPT and OpenAI SDK workflows. Sign up for 59API when you are ready to test the same Messages API integration with a pay-as-you-go provider.

Prêt à commencer ?

Connectez Claude et GPT en quelques minutes aux prix les plus bas, sans bridage. Inscrivez-vous pour votre clé API.

Inscription gratuite