Applications and Integration
Messages API mechanics (messages, tool use, streaming, vision, thinking, caching, structured output, stop reasons, batch), application boundaries on each surface, configuration and SDLC (CLAUDE.md, settings.json, model pinning, plugins, CI), and handling integration errors according to their documented semantics.
- Messages API Mechanics: message structure, tool use, streaming, vision, thinking, prompt caching, structured output, stop reasons; realtime vs batch
- Application Boundary and Surface Behavior: schema and session decisions
- Configuration and SDLC Integration: CLAUDE.md, settings.json, model version pinning, prompt versioning, plugin dependencies, CI
- Integration Resilience: streaming events, terminal events, error classes (rate limit, overloaded, invalid request, timeout), Files API
Domain overview
Domain 2, Applications and Integration, accounts for 20% of the exam version from Dec 7 (about 12 scored items) — the highest weight of the eight domains. Four skills:
| Skill (Exam Guide) | What the exam measures |
|---|---|
| Messages API Mechanics | Correct use of message structure, tool use, streaming, vision, thinking, prompt caching, structured output, and stop reasons; choosing realtime or batch |
| Application Boundary and Surface Behavior | How Claude interprets instructions on each surface, what content crosses the application boundary, and whether schema and session decisions meet the requirements |
| Configuration and SDLC Integration | Reading CLAUDE.md, settings.json, model version pinning, prompt versioning, plugin dependencies, and CI to determine the correct configuration and how a change affects each environment |
| Integration Resilience | Reading failing integration code and error output to find the defect: mishandled streaming events and terminal events, retries that do not distinguish error classes (rate limit, overloaded, invalid request, timeout), faulty multi-format ingestion through the Files API |
Common item shape: a Python/TypeScript snippet or an event sequence, plus a symptom, asking for the defect and a fix consistent with documented API semantics. Wrong options usually "mask" the symptom (raise max_tokens, retry every error) instead of fixing the cause.
(Source: CCDV-F Exam Guide, Domain 2)
Messages API: request, response, and stop reasons
Basic structure
resp = client.messages.create(
model="claude-haiku-4-5",
max_tokens=1024, # upper limit, not a target length
system="You are a ticket classification assistant.",
messages=[{"role": "user", "content": "Ticket: ..."}],
)
print(resp.content[0].text, resp.stop_reason, resp.usage)
- The API is stateless: every request must resend all the history it needs; the
user/assistantroles alternate. The system prompt goes in thesystemparameter, not in a message. contentis a list of content blocks (text,image,document,tool_use,tool_result,thinking…), not a string. Code that only readscontent[0].textbreaks when the first block isthinkingortool_use.- Changes across model generations: from Claude 4.6 onward, a prefilled final assistant message returns 400
invalid_request_error— use structured output or the system prompt instead; from Claude 4.7 onward, a non-defaulttemperaturereturns an error.
stop_reason |
Meaning | What the application should do |
|---|---|---|
end_turn |
Claude finished naturally | Use the result |
tool_use |
Claude wants to call a tool | Run the tool, send a tool_result, call again |
max_tokens |
Hit the output limit; the answer is truncated | Don't treat it as complete; raise the limit or continue deliberately |
stop_sequence |
Hit a custom stop sequence | Read stop_sequence to see which one |
pause_turn |
A long-running server tool was paused | Send the content back as the assistant turn to continue |
refusal |
Claude declined (HTTP is still 200) | Don't retry unchanged; stop_details gives the reason category |
Exam trap
refusal returns HTTP 200, so code that checks only the status code treats it as success. Resending the same request gets refused again — retrying is not the fix. Likewise, max_tokens is a deterministic outcome; an unchanged retry only costs money.
(Sources: Anthropic Academy: Building with the Claude API; Anthropic Academy: Claude Platform 101; Anthropic Skills: claude-api)
Tool use, structured output, thinking, and prompt caching
The tool-use loop
A tool is declared with a name, a description (ideally 3–4 sentences), and an input_schema. When stop_reason is tool_use, append resp.content unchanged to the history as the assistant turn, then send a user turn containing the tool_result blocks:
{"role": "user", "content": [
{"type": "tool_result", "tool_use_id": "toolu_01A", "content": "42 orders"},
{"type": "tool_result", "tool_use_id": "toolu_01B", "content": "Customer not found", "is_error": true}
]}
- Parallel tool use: one response can contain several
tool_useblocks; return everytool_resultin one user turn, exactly onetool_resultpertool_use, placed before any text — otherwise you get the 400tool_use ids were found without tool_result blocks immediately after. Splitting results across several messages makes Claude call tools in parallel less often. - A tool fails →
is_error: truewith a message; don't skip it. toolsmust be resent on every subsequent request.- The
inputof atool_useis a JSON object; parse it with a JSON library, don't match raw strings, because escaping can differ between model versions. - Forced
tool_choice(any,tool) returns 400 on some newer models (Claude Opus 5.5, Sonnet 5.5, Fable 5.1/5.2, Mythos 5.1/5.2);autoandnoneare still accepted.
Structured output
When the output is machine-read, use output_config: {"format": {...}} with a JSON schema (the old output_format parameter is deprecated); the SDK provides client.messages.parse() for validation. For tools, set "strict": true on the tool together with additionalProperties: false so the input is constrained by the schema. Note: citations are incompatible with output_config.format (returns 400).
Extended thinking
- Old syntax:
thinking={"type": "enabled", "budget_tokens": N}(minimum 1,024, less thanmax_tokens). From Claude 4.7 onward,enabledis not supported; usethinking={"type": "adaptive"}withoutput_config={"effort": ...}; conversely, models 4.5 and earlier don't acceptadaptive. - Thinking tokens are billed as output and count toward
max_tokens. - In a tool loop, send
thinking/redacted_thinkingblocks back unmodified — any edit returns a 400.
Prompt caching basics
- Mark content with
cache_control: {"type": "ephemeral"}; the prefix order is tools → system → messages; at most 4 breakpoints. - Default TTL is 5 minutes (refreshed on each use), with a 1-hour option; cache writes cost about 1.25× the input price, reads about 0.1×.
- Below the minimum length (e.g. 4,096 tokens for Haiku 4.5, 1,024 for Sonnet 4.6) there is no error, but
cache_creation_input_tokensandcache_read_input_tokensare both 0. A breakpoint placed after content that changes on every request (a timestamp) never hits.
Key point
When debugging caching, read usage: both cache fields at 0 → the prefix is too short or the breakpoint is misplaced; cache_creation always positive while cache_read is 0 → the prefix changes between requests.
(Sources: Anthropic Academy: Tool use with the Messages API; Claude Docs: Troubleshooting tool use; Claude Docs: Prompt caching)
Streaming and terminal-event semantics
With "stream": true, the API returns Server-Sent Events in this order:
| Event | Content | Notes |
|---|---|---|
message_start |
A message with empty content |
Opens the stream |
content_block_start |
Starts a block, with an index |
For tool use, the tool name appears here |
content_block_delta |
text_delta, input_json_delta (partial_json), thinking_delta, signature_delta |
Assemble by index |
content_block_stop |
Ends one block | Not the end of the message |
message_delta |
Message-level changes: stop_reason, usage (cumulative) |
Can occur more than once |
message_stop |
The message's terminal event | Only now is the response certainly complete |
ping events can be interleaved, and an error event can arrive mid-stream even though HTTP already returned 200, e.g. {"type": "error", "error": {"type": "overloaded_error", ...}} (the equivalent of a 529 without streaming). Unknown events must be ignored gracefully, because the API can add new event types.
blocks, stop_reason = {}, None
for event in stream:
if event.type == "content_block_delta" and event.delta.type == "text_delta":
blocks[event.index] = blocks.get(event.index, "") + event.delta.text
elif event.type == "message_delta":
stop_reason = event.delta.stop_reason
elif event.type == "message_stop":
break # only treat the response as done here, then branch on stop_reason
input_json_deltais partial JSON: accumulatepartial_jsonand parse it when that block'scontent_block_stoparrives.- If you don't need to handle individual events, the SDK offers
client.messages.stream(...)withtext_streamandget_final_message()(TypeScriptfinalMessage()). The SDK requires streaming for requests with a largemax_tokensto avoid HTTP timeouts. - Recovering an interrupted stream: with Claude 4.5 and earlier, send the received portion as the start of the assistant turn to continue; with Claude 4.6 onward (no more prefill), send a user turn containing the received portion plus an instruction to continue.
tool_useandthinkingblocks cannot be resumed partway — continue from the most recent text block.
Exam trap
A handler that treats the first content_block_stop as "done" cuts off later blocks (for example the text after thinking, or a tool_use) and never reads stop_reason. The correct fix: wait for message_stop and take stop_reason from message_delta. Raising max_tokens, switching to non-streaming, or retrying does not fix this defect.
Scenario example
A streaming chatbot sometimes shows truncated answers with no warning. The logs show the event sequence ending with message_delta carrying stop_reason: "max_tokens", then message_stop; the UI relies only on text_delta. Reasoning: the stream ends correctly; the defect is that the application ignores stop_reason. It needs to read message_delta and handle max_tokens (notify the user, continue deliberately, or raise the limit) instead of treating every finished stream as complete.
(Sources: Claude Docs: Streaming messages; CCDV-F Exam Guide, Domain 2 — Integration Resilience)
Vision, PDFs, and the Files API
- Images: a
{"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": ...}}block or a URL source. PDFs: adocumentblock withmedia_type: "application/pdf"; place documents before the question; enable"citations": {"enabled": true}when you need citations. - Files API: upload once, get a
file_id, and reference it many times instead of resending base64. The content block type must match the file's MIME type.
| Format | How to pass it | Notes |
|---|---|---|
| PDF, plain text | {"type": "document", "source": {"type": "file", "file_id": ...}} |
Citations can be enabled |
| Images (PNG, JPEG…) | An image block referencing the file_id |
Don't use document for images |
| .csv, .md | Upload with MIME text/plain, then use as text |
Declare the MIME type explicitly |
| .docx, .xlsx | Can't be used directly as a document; convert to text first |
Or process with code execution |
| Spreadsheets that need calculation | A container_upload block + the code execution tool |
The container has no network access |
The Files API originally required the beta header files-api-2025-04-14; current SDKs have a stable client.files namespace. Request size limits (413 request_too_large): Messages API 128 MB, Batch API 256 MB, Files API 500 MB.
Exam trap
An ingestion pipeline that "works for PDFs but fails for images and Excel files" usually attaches every file as a document block. The fix is to choose the block by MIME type: images → image, PDF/text → document, docx/xlsx → convert first or use container_upload.
(Sources: Anthropic Academy: Building with the Claude API (vision, PDF, citations); Anthropic Skills: claude-api (Files API); Claude Docs: Claude API errors)
Realtime or Message Batches
| Criterion | Messages API (realtime) | Message Batches API |
|---|---|---|
| Latency | Immediate | Most finish within 1 hour, at most 24 hours |
| Cost | Standard pricing | 50% discount |
| Scale | Bound by rate limits | Up to 100,000 requests or 256 MB per batch |
| Results | Returned directly | Matched by custom_id, in any order; kept for 29 days |
| Not supported | — | stream: true, fallbacks, max_tokens: 0… |
- Batches support vision, tool use, system prompts, multi-turn, and thinking; they are not subject to ramp limits.
- Validation happens asynchronously: parameter errors only surface during processing — test the request shape with the Messages API first.
- Result types are
succeeded,errored,canceled,expired; the last three are not billed.
Exam tip
"Thousands of documents processed overnight", "no immediate response needed", "reduce cost" → Message Batches. "The user is waiting", "streaming UI" → realtime. Batches are not a way around rate limits for tasks that need an immediate answer.
(Sources: Claude Docs: Batch processing; CCDV-F Exam Guide through Dec 6, Sample Question 1)
Application boundary and surface behavior
Each surface loads different context
| Surface | What Claude receives |
|---|---|
| Messages API | Only what is in the request: system, messages, tools; no CLAUDE.md, no memory of earlier sessions |
| Interactive Claude Code | CLAUDE.md from four stacked locations (managed policy, user, project, local), plus hooks, skills, plugins, MCP servers |
Headless Claude Code (-p) |
The same context as interactive; add --bare to skip auto-discovery (hooks, skills, plugins, MCP, CLAUDE.md) |
| Agent SDK | Only the sources listed in setting_sources |
| Managed Agents | The agent configuration (model, system prompt, tools) and the session's events |
Consequence: a rule that lives only in CLAUDE.md has no effect when the same prompt runs through the Messages API, through --bare in CI, or through the Agent SDK with setting_sources=[].
What content crosses the boundary
- API keys stay on the back end. Browser requests carry an
Originheader; a 401 with the messageCORS requests are not allowed for this Organizationis not a key problem — the call must go through your back end. - Tool results are data, not instructions: Claude treats instructions inside a
tool_resultas untrusted; real instructions belong in the user turn or the system prompt. - For agents with a sandbox, credentials should not enter the sandbox: use a vault or a proxy.
Schema and session decisions
- Machine-read output →
output_config.formator a strict tool; clear tool descriptions. - Sessions: because the API is stateless, the application decides which part of the history to resend (cost, context). In Claude Code, long sessions need a proactive
/compactwith instructions (e.g./compact Focus on the --version flag implementation) and a rewind to a checkpoint when they drift off course; for an objective review, use a new session or subagent. Multi-step headless runs: take thesession_idfrom the JSON output, thenclaude --resume.
Scenario example
A team moves a prompt that works well in Claude Code into a backend service that calls the Messages API; the output loses the company's standard format. Reasoning: the formatting conventions live in CLAUDE.md, and the Messages API sees only the request content. The conventions need to go into the service's system prompt (or a schema through output_config.format).
(Sources: Anthropic Academy: Claude Code in action; Claude Docs: Claude API errors; Claude Docs: Troubleshooting tool use)
Configuration and SDLC integration
CLAUDE.md and settings.json
- CLAUDE.md is guidance, not enforced configuration; the longer it gets, the more gets missed. Four locations are loaded together: managed policy (organization-wide, cannot be excluded), user, project (committed to the repo), local (ignored by git).
@pathimports are expanded inline at startup — they help organization but do not reduce context. Hard rules → hooks. - settings.json:
.claude/settings.json(project, shared with the team),.claude/settings.local.json(personal),~/.claude/settings.json(user). Managed settings are controlled by the platform team and can pin Claude Code's default model.
Plugin dependencies
A plugin packages skills, subagents, hooks, and MCP configuration into one installable unit; the .claude-plugin/plugin.json manifest requires only name (used for namespacing, e.g. /plugin-name:skill-name) and should include version to track updates. Plugin hooks run in addition to your hooks; if you move a hook into a plugin without removing it from settings.json, each hook runs twice. Plugins run code with your permissions — read them before installing.
Pinning models and versioning prompts
- Write model IDs explicitly in per-environment configuration. Some models have dated snapshots (e.g.
claude-opus-4-5-20251101; on Vertex AI useclaude-opus-4-5@20251101). - Switching models can break working code: prefill returns 400 from Claude 4.6, and
thinking: {"type": "enabled"}is no longer supported from Claude 4.7. Therefore prompts and models must be versioned with the code and reach production only after the evals are rerun — "version what ships so a model or prompt change does not silently break production". - Managed Agents: an agent is a versioned object; a referenced subagent is pinned to its version at the time the parent is created/updated, so to use a newer version you must update the parent agent.
Key point
"Which environments does this configuration change affect?" is answered by tracing the layers: managed policy/managed settings (the whole organization), user (one machine), project — .claude/settings.json and CLAUDE.md committed to the repo (everyone who clones the repo), local (one person, one repo), CLI flags in CI (--bare, --settings), and API requests (only the service sending that request).
CI
| Tool | Use when | Configuration points |
|---|---|---|
claude -p |
Your own pipeline, piping data in | --output-format json --json-schema → the structured_output field |
--bare |
CI needs the same setup on every machine | Skips auto-discovery; requires ANTHROPIC_API_KEY |
GitHub Action anthropics/claude-code-action@v1 |
Work that goes beyond review in CI | claude_args: --max-turns, --model, --allowedTools |
Permission mode dontAsk |
Unattended runs | Actions that would prompt are denied automatically, so the pipeline doesn't hang |
Exam trap
"The hook runs on my machine but not in CI" is usually not a bug: the hook lives in settings.local.json (personal machine only), or CI runs with --bare, which skips hooks, CLAUDE.md, and plugins. Work out which layer the configuration change lives in and which environments load that layer.
(Sources: Anthropic Academy: Claude Code in action (CLAUDE.md, headless, GitHub Actions, plugins, permission modes); Claude Certification exam prep: CCDV-F Prep Course — Accelerators & IP Contribution; Claude Docs: Multiagent orchestration)
Integration resilience: errors, retries, timeouts
| HTTP | error.type |
Retry? | Correct handling |
|---|---|---|---|
| 400 | invalid_request_error |
No | Fix the request; note that a 400 also appears when you hit a spend limit you set |
| 401 | authentication_error |
No | Fix the key; CORS error → call through the back end |
| 403 | permission_error |
No | Check workspace/organization permissions |
| 404 | not_found_error |
No | Check the endpoint and resource ID |
| 413 | request_too_large |
No | Reduce the size; use the Files API |
| 429 | rate_limit_error |
Yes, per retry-after |
A 429 caused by the tier's spend cap has no retry-after and keeps failing until the cap is lifted |
| 500 | api_error |
Yes, exponential backoff | Record the request_id if it recurs |
| 504 | timeout_error |
Depends | Long requests → streaming or Batch |
| 529 | overloaded_error |
Yes, backoff | System-wide overload, not your fault |
- The official SDKs retry automatically on transient errors (connection errors, rate limits, 5xx) with exponential backoff, 2 times by default, honoring
retry-after; adjust withmax_retries. The default timeout is 10 minutes; the SDK checks that non-streaming requests won't exceed 10 minutes — longer requests must stream. - Catch the SDK's typed exceptions (e.g.
anthropic.NotFoundError), most specific class first; don't match on message strings. Log therequest_id(therequest-idheader). - Rate limits are measured in RPM, ITPM, and OTPM with a token bucket; tokens read from cache don't count toward ITPM. A sudden traffic spike can hit a 429 ramp limit even below your quota → ramp up gradually.
Key point
Keep three classes of outcome apart: transient errors (429 with retry-after, 500, 529, connection errors) → retry with backoff; request errors (400, 401, 403, 404, 413) → fix, don't retry; deterministic outcomes returned with 200 (max_tokens, refusal) → handle in application logic.
Scenario example
A worker retries every exception 5 times with a fixed 1-second delay. When a model ID is mistyped, the logs fill with repeated 404s; under heavy load, a flood of 529 retries makes the overload worse. Reasoning: the retry logic does not distinguish error classes. Fix: don't retry 4xx (except 429); retry 429/5xx/529 with exponential backoff that honors retry-after — or rely on the SDK's built-in retries.
(Sources: Claude Docs: Claude API errors; Claude Docs: Rate limits)
Quick summary
- Domain 2 = 20%: Messages API Mechanics, Application Boundary and Surface Behavior, Configuration and SDLC Integration, Integration Resilience.
- The API is stateless;
contentis a list of blocks;max_tokensis an upper limit; Claude 4.6+ returns 400 on prefill. - Stop reasons:
end_turn,tool_use,max_tokens,stop_sequence,pause_turn,refusal(HTTP 200, don't retry). - All
tool_resultblocks for a turn go in one user message, with the matchingtool_use_id, before any text; a failed tool →is_error: true. - Structured output:
output_config.format, strict tools; citations can't be combined withoutput_config.format. - Send thinking blocks back unmodified; Claude 4.7+ uses
adaptive+effort. - Caching: tools → system → messages, at most 4 breakpoints; below the minimum length nothing is cached and no error is raised.
- Streaming:
message_stopis the terminal event;stop_reasonis inmessage_delta; anerrorevent can arrive after HTTP 200. - Files API: the block must match the MIME type; convert docx/xlsx first; spreadsheets that need calculation →
container_upload+ code execution. - Batches: 50% discount, at most 24 hours, results matched by
custom_id, no streaming. - The Messages API doesn't read CLAUDE.md;
--bareskips hooks, plugins, and CLAUDE.md; the Agent SDK followssetting_sources. - Instructions inside a
tool_resultare treated as untrusted; API keys never go in the browser. - Pin model IDs per environment, version prompts with the code, run evals before switching models.
- Retry 429/500/529 with backoff and
retry-after; don't retry 400/401/403/404/413; the SDK retries 2 times by default.