← Blog

Claude API Structured Data Extraction Tutorial

2026-11-20 · 5 min read · SubToAPI Team

What this tutorial covers

If you landed here, you probably have a pile of unstructured text — invoices, support tickets, resumes, contracts, emails — and you want reliable JSON out the other end instead of a wall of prose. The Claude API can do this well, but only if you set it up correctly: the wrong approach gives you inconsistent formatting, missing fields, and JSON that breaks your parser on the tenth request.

This tutorial walks through the actual pattern that works in production: defining a tool (function) schema that forces Claude to respond in a fixed shape, validating the output, and handling edge cases like missing data or ambiguous input. By the end you'll have a working extraction pipeline you can adapt to your own data.

Why "just ask for JSON" doesn't scale

The naive approach is to prompt Claude with "respond only in JSON" and parse the text response. This works in a demo and fails in production because:

The reliable fix is tool use. Instead of asking Claude to describe JSON in words, you give it a tool definition with a strict input schema, and the model returns a structured tool call matching that schema instead of free text. This is the same mechanism used for agentic function calling, repurposed for extraction.

Step 1: Define your extraction schema

Say you're extracting structured data from customer support emails: sentiment, category, and any mentioned order numbers.

{
  "name": "extract_ticket_data",
  "description": "Extract structured fields from a customer support email",
  "input_schema": {
    "type": "object",
    "properties": {
      "sentiment": {
        "type": "string",
        "enum": ["positive", "neutral", "negative"]
      },
      "category": {
        "type": "string",
        "enum": ["billing", "bug_report", "feature_request", "account", "other"]
      },
      "order_numbers": {
        "type": "array",
        "items": { "type": "string" }
      },
      "summary": {
        "type": "string",
        "description": "One sentence summary of the issue"
      }
    },
    "required": ["sentiment", "category", "summary"]
  }
}

This is the core trick: enum locks down categorical fields so you never get "Negative" in one response and "somewhat negative" in another. required forces the model to populate critical fields rather than skipping them.

Step 2: Send the request with the tool attached

curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-4-5",
    "max_tokens": 1024,
    "tools": [{
      "name": "extract_ticket_data",
      "description": "Extract structured fields from a customer support email",
      "input_schema": { "...": "see schema above" }
    }],
    "tool_choice": { "type": "tool", "name": "extract_ticket_data" },
    "messages": [{
      "role": "user",
      "content": "Subject: Order #88213 still not shipped after 2 weeks. This is ridiculous, I need a refund now."
    }]
  }'

The tool_choice field is the important part. Setting it to force the specific tool means Claude cannot respond with plain text at all — it must call extract_ticket_data with arguments matching your schema. This removes almost all the formatting variance you'd get from free-text prompting.

Step 3: Parse the tool call from the response

The response contains a tool_use content block with the extracted arguments already as a JSON object — no string parsing needed:

const response = await client.messages.create({ /* ...request above... */ });

const toolCall = response.content.find(block => block.type === "tool_use");
const extracted = toolCall.input;

console.log(extracted);
// { sentiment: "negative", category: "billing", order_numbers: ["88213"], summary: "..." }

Because input is already parsed JSON matching your schema, you skip the fragile step of regex-stripping markdown fences or hoping JSON.parse doesn't throw.

Handling edge cases

Real-world text is messy. A few patterns that help:

Running this at scale

Once your schema and prompt are stable, the main production concerns become throughput, retries, and key management rather than extraction quality. If you're running extraction jobs across a team or product and don't want to manage Anthropic account provisioning, rate-limit handling, and per-project usage tracking yourself, SubToAPI turns your existing Claude access into a standard HTTPS API with its own sub_live_ keys, so each pipeline or environment gets its own key and usage metadata without touching your primary Anthropic credentials. Tool use works the same way — see the tools docs and messages docs for request shapes identical to what's shown above. If you want to test an extraction pipeline before committing, the free trial at signup covers that, and pricing scales from solo projects to team seats.

questions

Does structured extraction cost more tokens than a plain-text prompt? Slightly more on the output side because you're returning a JSON tool call instead of a short sentence, but input tokens stay the same, and you save on post-processing since there's no cleanup logic to parse markdown-wrapped JSON.

Can I extract multiple different schemas from the same document in one call? Yes — define multiple tools and let the model call more than one, or combine fields into a single schema if they're always needed together. A single well-designed schema is usually faster and cheaper than multiple tool calls.

What if Claude returns a tool call with a field that doesn't match my enum? This is rare when tool_choice forces the specific tool, but always validate server-side anyway. Treat any mismatch as a failed extraction and retry with a clarifying follow-up message rather than silently coercing the value.

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 →