← Blog

Claude API JSON Schema Validation Example

2026-11-17 · 4 min read · SubToAPI Team

Claude doesn't have a native "response_format: json_schema" flag like some other APIs. Instead, you get structured, schema-validated JSON output by defining a tool with an input_schema and forcing Claude to call it. This gives you the same guarantee — output that matches your schema — using a mechanism that's actually more flexible because it supports nested objects, enums, required fields and arrays out of the box.

This article walks through a complete, working example: defining the schema, forcing tool use, parsing the result, and handling validation failures gracefully.

Why Claude handles this differently

Claude's tool-use feature was built for function calling, but it doubles as a JSON schema enforcement mechanism. When you define a tool with an input_schema (standard JSON Schema format) and set tool_choice to force that specific tool, Claude's output arrives as a structured tool_use block instead of free text. The model is trained to produce arguments that conform to the schema — types, required fields, enums and all.

This is more reliable than asking Claude to "return JSON" in a prompt, because:

A complete example: extracting structured data

Suppose you want to extract a product review into a structured object with a rating, sentiment, and list of mentioned features.

{
  "name": "submit_review_analysis",
  "description": "Submit structured analysis of a product review",
  "input_schema": {
    "type": "object",
    "properties": {
      "rating": {
        "type": "integer",
        "minimum": 1,
        "maximum": 5
      },
      "sentiment": {
        "type": "string",
        "enum": ["positive", "neutral", "negative"]
      },
      "features_mentioned": {
        "type": "array",
        "items": { "type": "string" }
      },
      "summary": {
        "type": "string",
        "maxLength": 200
      }
    },
    "required": ["rating", "sentiment", "features_mentioned", "summary"]
  }
}

Here's the full request using curl against the Claude Messages API:

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": "submit_review_analysis",
      "description": "Submit structured analysis of a product review",
      "input_schema": {
        "type": "object",
        "properties": {
          "rating": { "type": "integer", "minimum": 1, "maximum": 5 },
          "sentiment": { "type": "string", "enum": ["positive", "neutral", "negative"] },
          "features_mentioned": { "type": "array", "items": { "type": "string" } },
          "summary": { "type": "string", "maxLength": 200 }
        },
        "required": ["rating", "sentiment", "features_mentioned", "summary"]
      }
    }],
    "tool_choice": { "type": "tool", "name": "submit_review_analysis" },
    "messages": [{
      "role": "user",
      "content": "Review: The battery lasts all day and the camera is great, but the app crashes constantly. 3/5 stars."
    }]
  }'

The response contains a tool_use content block with input matching your schema:

{
  "type": "tool_use",
  "name": "submit_review_analysis",
  "input": {
    "rating": 3,
    "sentiment": "neutral",
    "features_mentioned": ["battery", "camera", "app stability"],
    "summary": "Decent battery and camera, but frequent app crashes bring the rating down."
  }
}

Parsing and validating the response in JavaScript

Even though Claude is strongly guided by the schema, you should still run a validation pass in your own code — especially for production pipelines where a malformed field could break downstream logic.

import Ajv from "ajv";

const schema = {
  type: "object",
  properties: {
    rating: { type: "integer", minimum: 1, maximum: 5 },
    sentiment: { type: "string", enum: ["positive", "neutral", "negative"] },
    features_mentioned: { type: "array", items: { type: "string" } },
    summary: { type: "string", maxLength: 200 }
  },
  required: ["rating", "sentiment", "features_mentioned", "summary"]
};

const ajv = new Ajv();
const validate = ajv.compile(schema);

function extractToolInput(response) {
  const toolBlock = response.content.find(b => b.type === "tool_use");
  if (!toolBlock) throw new Error("No tool_use block in response");
  return toolBlock.input;
}

const data = extractToolInput(response);

if (!validate(data)) {
  console.error("Schema validation failed:", validate.errors);
  // retry, log, or fall back to a default object
} else {
  console.log("Valid structured output:", data);
}

Using Ajv (or any JSON Schema validator) as a second check is cheap and catches edge cases — Claude is good but not perfect, and defensive validation avoids silent failures in automated pipelines.

Handling validation failures

A few practical patterns worth building in:

Running this through SubToAPI

If you're calling Claude through SubToAPI, the same tool-calling and schema-validation pattern works unchanged — you just swap the endpoint and auth header. Requests go to https://api.subtoapi.app/v1/messages with Authorization: Bearer $SUBTOAPI_KEY, and the tools and tool_choice fields behave identically to the native API. This is useful if you want usage metadata, team seats, or a single dashboard key across multiple apps while keeping the exact same schema-enforcement logic. See the tool use docs and messages API reference for the full parameter list, or the quickstart to get an API key in a few minutes.

questions

Does Claude support a native json_schema response format like OpenAI? No. Claude enforces structured output through tool definitions with input_schema, forced via tool_choice. The result is equivalent — strongly typed, schema-conformant JSON — just implemented differently.

Should I still validate Claude's JSON output on my end? Yes. Claude follows schemas closely but isn't infallible. Run the output through a validator like Ajv before passing it downstream, especially in automated or high-volume pipelines.

Can I use nested objects and arrays in the schema? Yes. input_schema accepts standard JSON Schema, including nested objects, arrays, enums, and constraints like minimum, maxLength, and required fields.

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 →