← Blog

Claude API Prompt Templates for Structured Output

2026-10-27 · 5 min read · SubToAPI Team

If you're searching for Claude API prompt templates for structured output, you're probably trying to get consistent JSON (or XML, or some other machine-readable format) back from Claude instead of free-flowing prose. The good news: Claude is quite good at following output format instructions when you give it a clear template and a few constraints. The bad news: "just ask nicely" often isn't enough for production use — you need a repeatable pattern.

This article gives you a set of working prompt templates you can copy, adapt, and reuse, plus the rules that make them reliable instead of flaky.

Why structured output requests fail

Before the templates, it helps to know why Claude sometimes ignores your format request:

Every template below addresses these four problems directly.

Template 1: Strict JSON with a schema description

Use this when you need a fixed set of fields and types, like extracting structured data from text.

You are a data extraction engine. Extract the following fields from the text below and return ONLY valid JSON, with no markdown fences, no explanation, and no trailing text.

Schema:
{
  "name": "string",
  "email": "string or null",
  "company": "string or null",
  "intent": "one of: sales, support, billing, other"
}

Text:
"""
{{input_text}}
"""

Return only the JSON object.

The key moves: give the schema as literal JSON (types as strings is fine, Claude understands it), wrap the input in triple quotes so it's unambiguous where the data starts and ends, and repeat "return only the JSON object" at the end — repetition at the tail of the prompt matters more than you'd think.

Template 2: JSON with explicit null handling

Missing data is the most common source of broken parsing. Be explicit about what happens when a field can't be found.

Extract structured data from the text. If a field cannot be determined, use null — never omit the key and never invent a value.

Fields: title, price, currency, in_stock (boolean), tags (array of strings, empty array if none).

Return only valid JSON matching this shape, nothing else.

Template 3: Few-shot example for tricky formats

When the output format is unusual (nested objects, specific enums, date formats), describing it isn't enough — show one example.

Convert the meeting notes into structured JSON. Follow the example format exactly, including date format (YYYY-MM-DD) and the "action_items" structure.

Example input:
"Call with Dana on March 3rd. She'll send the contract, we'll review by Friday."

Example output:
{
  "date": "2024-03-03",
  "participants": ["Dana"],
  "action_items": [
    {"owner": "Dana", "task": "send the contract", "due": null},
    {"owner": "us", "task": "review contract", "due": "2024-03-08"}
  ]
}

Now convert this input:
"""
{{meeting_notes}}
"""

One well-chosen example usually outperforms three extra sentences of explanation.

Template 4: Pair structured output with tool use

If your use case is well-defined and you're calling Claude programmatically, defining a tool with a JSON schema is more reliable than prompting for JSON in free text, because Claude is trained to populate tool call arguments precisely rather than narrate around them.

{
  "name": "extract_contact",
  "description": "Extract contact details from a message",
  "input_schema": {
    "type": "object",
    "properties": {
      "name": {"type": "string"},
      "email": {"type": "string"},
      "urgency": {"type": "string", "enum": ["low", "medium", "high"]}
    },
    "required": ["name", "urgency"]
  }
}

With tool use, Claude returns a tool_use block with arguments that already match your schema, so you skip the "strip the markdown fence and hope it's valid JSON" step entirely. If you're routing requests through SubToAPI, the /docs/tools guide walks through defining and parsing tool calls against the same /v1/messages endpoint you already use for regular prompts.

Template 5: Output format locked with a system prompt

For apps that always need the same format, put the format rule in the system prompt instead of repeating it in every user message. This keeps your per-request prompts shorter and the rule more durable across a conversation.

System: You are an API backend. Every response you produce must be a single valid JSON object with no additional text, markdown, or commentary. If you cannot fulfill a request, return {"error": "<reason>"} instead of explaining in prose.

This pattern is especially useful if you're building on SubToAPI, since the system prompt travels with every call to /v1/messages — see /docs/messages for the request shape and how system prompts interact with streaming responses.

Validating what comes back

Even with a good template, always parse defensively:

function parseClaudeJSON(text) {
  const cleaned = text.trim().replace(/^```json\n?|```$/g, '');
  try {
    return JSON.parse(cleaned);
  } catch (err) {
    throw new Error(`Invalid JSON from model: ${err.message}`);
  }
}

Strip markdown fences defensively (some prompts still leak them despite instructions), and always wrap JSON.parse in a try/catch with a retry path — asking Claude to "fix the JSON, it was invalid" as a follow-up message is usually enough to recover.

Putting it into a pipeline

If you're building this into a product, a typical flow looks like:

  1. Build the prompt from a template with the actual data interpolated.
  2. Send it to Claude via /v1/messages (or /docs/quickstart if you're setting this up for the first time).
  3. Parse and validate defensively.
  4. Retry once with an explicit "your last response was invalid JSON, return only valid JSON" message if parsing fails.
  5. Log failures so you can tighten the template over time.

SubToAPI exposes the same Messages API surface so these templates work unchanged — streaming structured output is possible too (see /docs/streaming), though for strict JSON you generally want to buffer the full response before parsing rather than parsing partial chunks.

questions

Do I need to tell Claude not to use markdown code fences? Yes, if you want raw JSON. Claude defaults to wrapping JSON in triple-backtick fences unless you explicitly say "no markdown fences, no explanation." Add that line to every structured-output prompt.

Is tool use better than prompting for JSON? For well-defined, repeatable extraction tasks, yes — tool use with an input_schema is more reliable because Claude is handling a function call rather than free text. For open-ended or exploratory tasks, a well-written JSON prompt template is simpler to iterate on.

What temperature should I use for structured output? Lower is generally safer — temperature 0 to 0.3 reduces formatting drift and invented fields. Higher temperatures are fine for creative tasks but increase the chance of malformed or inconsistent structured output.

Turn your Claude access into an HTTPS API

SubToAPI gives you application API keys, streaming, tool use and usage insights on top of your existing Claude access — set up in minutes.

Start free  Read the quickstart →