Structured-output features and validation in code

Study time
≈ 3 h (estimate)
Needs
L1-M05-L01
Updated
2026-11-06

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L1-M05 · Duration: ~180 min (estimate, including the independent exercise) · Previous: L01 · Next: L03 - Function calling basics: tool definitions and tool-call responses

1. Introduction

In L1-M02 you saw that a prompt asking for "answer in JSON" can still get back text with JSON in it, JSON with missing fields, or JSON with the wrong structure. The Claude API has a structured outputs feature: you send a JSON Schema, and the answer is constrained to that schema.

This feature removes a great many errors, but it does not remove the tester's job. There are constraints the API does not enforce, there are cases where the output does not match the schema, and there are cases where the application code handles things wrongly. This lesson teaches you to test the integration layer around structured output: whether the request that is sent is right, and what the application does with each kind of response.

2. Learning objectives

  1. Explain output_config.format and strict tool use, and what they guarantee.
  2. Distinguish keywords that the API supports from keywords that must be checked in code.
  3. Implement a safe processing order: stop reason, then JSON parsing, then the full schema.
  4. Write tests for the failure paths: a constraint violation, wrong enum capitalisation, a refusal, a cut-off answer, an answer that is not JSON.
  5. Describe the behaviour of messages.parse() in SDK 2.3.0 and what it means for error handling.

3. Prerequisites and tools

  • L01: JSON Schema and validate().
  • L1-M03: the fake API, stop reasons, pytest.raises.

4. Concepts

4.1 Two features

According to Anthropic's documentation on 2026-10-31:

  • JSON outputs: "The request carries the schema in output_config.format with type: "json_schema"" [R1]. The answer is text containing JSON that follows the schema.
  • Strict tool use: "Setting strict: true on a tool definition guarantees Claude's tool inputs match your JSON Schema by constraining the model's token sampling to schema-valid outputs" [R2]. You will use it in L03.

Everyday example. A restaurant's online booking form: the "Number of guests" box is a drop-down from 1 to 10, so nobody can type "about twelve people"; the "Notes" box is free text. Structured output turns the model's answer into the drop-down instead of the free-text box. But a drop-down only guarantees the shape: it does not know whether the restaurant still has a table for 10 tonight.

4.2 Unsupported keywords

The documentation lists the keywords that are not supported, among them "Numerical constraints (such as minimum, maximum, multipleOf)", "String constraints (minLength, maxLength)", and "additionalProperties set to anything other than false". Using them gets you a 400 error [R1].

So a correct application has two schemas:

Schema Where it is used In the lab
The full schema (the contract) Checked in code, after the response arrives TICKET_SCHEMA
The schema sent to the API output_config.format.schema api_schema(TICKET_SCHEMA) drops minimum, maximum, minLength, maxLength, pattern

The documentation has a separate section on pattern (regular expressions), which is supported with limits, and says that JSON outputs and strict tool use share these limits [R1]. The lab still drops pattern from the schema it sends. This is a deliberate choice of the lab, not a requirement of the API: every format rule is checked in one place, in the application's code. In a real project you may keep pattern in the schema you send, but you should still check it again in code, because the limits of the supported regular expressions may differ from the regular expression you wrote.

A typical integration bug: dropping constraints from the schema that is sent, and then forgetting to check them again in code. Then priority: 7 is treated as valid, even though the contract says 1-5.

Worked example: one field, two schemas. Print priority in the full schema and in the schema that is sent:

python -c "import json; from lab.schemas import TICKET_SCHEMA, api_schema; print(json.dumps(TICKET_SCHEMA['properties']['priority'])); print(json.dumps(api_schema()['properties']['priority']))"
{"type": "integer", "minimum": 1, "maximum": 5}
{"type": "integer"}
Constraint on priority Who checks it?
"type": "integer" The API (it is in the schema that is sent) and validate()
"minimum": 1, "maximum": 5 Only validate() in code: the API never sees them

Output run on 2026-11-06 on Python 3.14.6 and 3.12.3, Linux, identical on both versions; so is every other output in this lesson.

Good vs bad: a test for a constraint dropped from the schema that is sent.

Weak Good
The fake reply is a valid ticket; assert that ok is True The fake reply has priority: 7; assert error == "schema_violation" and that details contains maximum of 5
Green even after the code has removed the validation step Fails as soon as the validation step is removed or uses the cut-down schema by mistake

The weak test only proves the happy path. Only a reply that breaks the constraint tells you the constraint is still checked somewhere.

4.3 When the output does not match the schema

The documentation states the cases clearly [R1]:

  • Refusal: "The output might not match your schema because the refusal message takes precedence over schema constraints."
  • max_tokens: "The output might be incomplete and not match your schema."
  • Enum capitalisation: "Structured outputs don't guarantee the capitalization of string enum and const values." If the contract says refund, Refund can still appear.

The consequence: check the stop reason before parsing. A refusal that is parsed into an "invalid JSON" error is a wrong error message, and it hides the real cause.

Everyday example. The receipt printer at a till runs out of paper halfway: the receipt has only its top half (max_tokens). Or the cashier refuses to print because the transaction is blocked (refusal). An accountant who reads the receipt without the note "printer out of paper" books it wrongly and then reports "receipt printed in a bad format". The reason for stopping must be read before the content.

Good vs bad: the order of handling.

# Weak: parse first
data = json.loads(raw)                 # a refusal lands here and is reported as "invalid_json"

# Good: stop reason first, then parse, then the full schema
if response.stop_reason == "refusal":
    return _result(False, error="refused")
data = json.loads(raw)

With the weak version, every refusal becomes invalid_json on the dashboard: exactly situation 2 in section 7. The good version returns refused, so the dashboard reader knows the issue is content policy, not the parser.

4.4 The SDK's messages.parse()

The Python SDK has client.messages.parse(output_format=Model), where Model is a pydantic class [R1]. The documentation says the SDK will "Remove unsupported constraints … Update descriptions by adding each unsupported constraint to the field's description … Add additionalProperties: false to all objects … Validate responses against your original schema" [R1].

The lab observed the following with anthropic 2.3.0 (2026-10-31, against the fake API) and recorded it in tests:

  • The schema that is sent has no maximum; the field's description becomes "{maximum: 5, minimum: 1}".
  • A reply that violates a constraint makes parse() raise pydantic.ValidationError.
  • A reply with the stop reason refusal or max_tokens whose text is not complete JSON also makes parse() raise pydantic.ValidationError (json_invalid). Your code cannot read the stop reason before the exception happens.

This does not mean that parse() is wrong. It means that code using parse() must catch ValidationError and must not report it as "the model returned bad JSON" by default. The lab's classifier uses create() to check the stop reason first, and then validates on its own.

Worked example: one refusal, read two ways. Save this as try_l02_parse.py in the lab folder and run python try_l02_parse.py:

import os
os.environ["ANTHROPIC_API_KEY"] = "sk-test-fake-key-0000"     # fake key: the fake API only

import pydantic
from pydantic import BaseModel

from lab.classifier import classify, make_client
from lab.fake_api import FakeClaudeAPI, message, text


class Ticket(BaseModel):
    category: str
    priority: int


with FakeClaudeAPI() as api:
    client = make_client(api.base_url)
    api.queue(message(text("Xin lỗi, mình không thể"), stop_reason="refusal"))
    try:
        client.messages.parse(model="claude-opus-5-5", max_tokens=100, output_format=Ticket,
                              messages=[{"role": "user", "content": "x"}])
    except pydantic.ValidationError as exc:
        print("parse():   ", type(exc).__name__, exc.errors()[0]["type"])
    api.queue(message(text("Xin lỗi, mình không thể"), stop_reason="refusal"))
    print("classify():", classify(client, "x")["error"])
parse():    ValidationError json_invalid
classify(): refused

parse() raises a ValidationError of type json_invalid: from the exception you cannot tell that the model refused. classify() reads the stop reason first, so it returns refused. Delete the file when you are done.

5. Technical deep dive

5.1 lab/classifier.py

response = client.messages.create(..., output_config={"format": {"type": "json_schema",
                                                                  "schema": api_schema(TICKET_SCHEMA)}})
if response.stop_reason == "refusal":    return _result(False, error="refused")
if response.stop_reason == "max_tokens": return _result(False, error="truncated")
data = json.loads(raw)                    # invalid_json nếu thất bại
problems = validate(data)                 # schema ĐẦY ĐỦ; schema_violation nếu có lỗi

In English: the two comments read "invalid_json if it fails" and "the FULL schema; schema_violation if there are errors".

The result is always {"ok", "ticket", "error", "details"}, so the code that calls it never has to guess.

The code above is shortened. The real file checks two more cases, so the full table is:

stop_reason error from classify() Parsed?
refusal refused No
max_tokens, model_context_window_exceeded truncated No
end_turn invalid_json, schema_violation, or ok: True Yes
Any other value (for example pause_turn) unexpected_stop, with the stop reason in details No

The last row is an allow list: only end_turn is trusted, instead of listing every bad value. test_other_stop_reasons_are_not_trusted checks the two lower rows.

5.2 The fake API checks the request

lab/fake_api.py returns a 400 error when the schema in output_config uses a keyword that the documentation says is not supported, or when an object lacks additionalProperties: false. This lets a test catch the bug "sending the full schema to the API" without the real API. The real API may check more.

Worked example: sending the full schema by mistake. Save this as try_l02_400.py in the lab folder and run python try_l02_400.py:

import os
os.environ["ANTHROPIC_API_KEY"] = "sk-test-fake-key-0000"     # fake key: the fake API only

import anthropic

from lab.classifier import make_client
from lab.fake_api import FakeClaudeAPI
from lab.schemas import TICKET_SCHEMA, api_schema

with FakeClaudeAPI() as api:
    client = make_client(api.base_url)
    for name, schema in (("full schema", TICKET_SCHEMA), ("api_schema()", api_schema())):
        try:
            client.messages.create(model="claude-opus-5-5", max_tokens=100,
                                   messages=[{"role": "user", "content": "x"}],
                                   output_config={"format": {"type": "json_schema", "schema": schema}})
            print(name, "-> 200")
        except anthropic.BadRequestError as exc:
            print(name, "-> 400")
            for problem in exc.body["error"]["message"].split("; "):
                print("  ", problem)
full schema -> 400
   output_config.format.schema.properties.priority: 'minimum' is not supported
   output_config.format.schema.properties.priority: 'maximum' is not supported
   output_config.format.schema.properties.summary: 'minLength' is not supported
   output_config.format.schema.properties.summary: 'maxLength' is not supported
api_schema() -> 200

The four rejected keywords are the four the documentation lists as unsupported (section 4.2). The fake does not reject pattern and $schema: pattern is supported with limits, and the lab drops it by its own choice. With api_schema(), the request succeeds. Delete the file when you are done.

5.3 The Python you need for this lesson

  • try: ... except json.JSONDecodeError as exc: catches a JSON parsing error.
  • pydantic (a library that comes with the SDK): class Ticket(BaseModel): priority: int = Field(ge=1, le=5) declares a data type with constraints. ge means "greater or equal", le means "less or equal".
  • pytest.raises(Error, match="...") asserts that an exception happens and that its message contains that string.

6. The QA perspective

Path Fake reply Expected result
Valid JSON that matches the schema ok: True
Violation of a constraint dropped from the schema that is sent priority: 7 schema_violation
Wrong enum capitalisation "Refund" schema_violation (or a normalisation rule that the contract states clearly)
Refusal stop_reason: refusal refused, no parsing
Cut off stop_reason: max_tokens truncated, no parsing
Not JSON "category: refund" invalid_json
Request - The schema that is sent equals api_schema(...) and has no unsupported keyword
  • What can go wrong: trusting structured output and therefore not validating; validating with the stripped schema; parsing before checking the stop reason; reporting every error as "invalid JSON".
  • How to report: record the stop reason, the raw text of the reply and the list of validation errors.

7. Real-world scenarios

Scenario 1 (fictional): priority 7. A system picks a queue by priority from 1 to 5. After turning on structured output, the team drops maximum from the schema to get rid of the 400 errors, and deletes the validation step too, "because the API already guarantees it". A ticket with priority: 7 makes the queue-selection code fail with an index error. The test "a constraint dropped from the schema that is sent is still checked in code" would catch this bug.

Scenario 2 (fictional): a refusal reported as bad JSON. The dashboard reports 2% "the model returned bad JSON". When the tester looks at the stop reasons, most of them are refusal, for messages with sensitive content. That is a completely different problem that needs completely different handling. The lesson: classify errors by stop reason first.

8. Hands-on tutorial

8.1 Running the demo

python -m lab.demo l02

Output (copied from a real run, 2026-10-31):

removed before sending: ['$schema', 'maxLength', 'maximum', 'minLength', 'minimum', 'pattern']
valid        ok=True  error=None []
priority 7   ok=False error=schema_violation ['$.priority: 7 is greater than the maximum of 5']
enum casing  ok=False error=schema_violation ["$.category: 'Refund' is not one of ['order_status', 'refund', 'damaged_item', 'account', 'other']"]
refusal      ok=False error=refused []
cut off      ok=False error=truncated []
not JSON     ok=False error=invalid_json ['Expecting value: line 1 column 1 (char 0)']

The first line lists the keywords dropped before sending. The six lines after it are the six paths of §6, each line with a different error.

8.2 Running the tests

python -m pytest tests/test_l02_structured.py -v

The three test_sdk_parse_... tests (just before the last test of the file) are characterization tests for messages.parse(): they record the observed behaviour of SDK 2.3.0. If a later SDK version changes that behaviour, these tests fail and remind you to read §4.4 again.

8.3 Troubleshooting

Symptom Cause Fix
BadRequestError: ... 'minimum' is not supported The full schema was sent to the API Send api_schema(...), validate the full schema in code
TypeError: Could not resolve authentication method Running code outside pytest without an API key The tests and the demo set a fake API key; do not use a real API key for the lab
pydantic.ValidationError from parse() with a refusal The behaviour recorded in §4.4 Catch the exception, or use create() and check the stop reason

9. Independent exercise

Problem: Add tests for the failure paths that the lesson has not tested yet.

Requirements: complete exercises/test_l02_classifier_failures.py:

  1. TODO 1: a summary 201 characters long.
  2. TODO 2: needs_human is missing.
  3. TODO 3: the reply text contains "priority" twice (3, then 9). Decide what classify() must return, write the test, and explain it in one sentence based on L01.

Test data: the ticket in tests/test_l02_structured.py.

Deliverable: the completed test file and the one-sentence explanation for TODO 3.

Acceptance criteria: the test file passes; each test asserts both error and the content of details.

Hint: for TODO 3, do not build the JSON with json.dumps (it never produces duplicate names). Write the reply text by hand, or use .replace(...) on the JSON string.

9.1 Extra exercise: a failure breakdown that does not call a refusal "bad JSON" (20-30 minutes)

Problem: situation 2 in section 7: the dashboard says "the model returns bad JSON", but most of those replies are refusals. You write a function that counts classify() results by error kind, so the dashboard names the real cause.

Requirements:

  1. Run python -m pytest exercises/test_l02_extra_breakdown.py once, untouched: 4 failed, each failure starting with TODO.
  2. Write failure_breakdown(api, client, replies): for each (text, stop_reason) pair, queue the reply on the fake, call classify(client, "x"), and count by error (None counts as "ok"). Do not guess the error kind from the text yourself.
  3. In TODO 2, before running, work out by hand: among the replies that are not ok, what share are refusals? Write the division as a comment.

Acceptance criteria: 4 passed; reply 7 (a refusal whose text starts like JSON) is counted as refused, not invalid_json.

Hint: each reply is one request, so api.queue(...) one reply and call classify right away. Count the 10 replies in REPLIES by hand first: how many are end_turn with valid JSON?

9.2 Real-world scenario: a bank's card-complaint classifier (fictional)

Context. The fictional bank NganHangXanh uses structured output to classify card-complaint messages into the JSON {"category": "lost_card" | "fraud" | "fee" | "other", "urgency": 1-3, "card_last4": "4 digits" | null}. urgency 3 blocks the card at once. In the first week, the dashboard reports 3% "the model returns bad JSON". The developers propose: "drop the validation step in code entirely, because structured output already guarantees the schema".

Task: write (a) a table of test cases for the six paths in section 6, each with a concrete fake reply and an expected result; (b) a short bug report for the dashboard; (c) a decision note (5-8 sentences) answering the developers' proposal.

A good answer has:

  • A case with urgency: 4 (a constraint dropped from the schema that is sent) whose expected result is a schema error and no card block
  • A case with "category": "Fraud" (wrong case) with a clear decision: reject it, or normalise it by a rule written in the contract
  • The refusal case and the max_tokens case expect something other than invalid_json, with no parsing
  • The bug report says how to reproduce: recount the 3% by each reply's stop_reason, with the numbers
  • The decision note rejects the proposal to drop validation, cites the documentation (refusal, max_tokens, enum capitalisation, unsupported keywords) and names the consequence for customers (a card blocked by mistake, or a compromised card not blocked)
  • No conclusion rests on a single run with a real model

10. Knowledge check

0/20 done · Results are kept in this browser only.

P02 · True or false

With structured outputs, the application no longer needs to validate the JSON.

P03 · Short answer

Why must you check the stop reason before parsing the JSON?

P04 · Short answer

Name two things that messages.parse() does to the schema before sending it, according to the documentation.

P05 · Short answer

(Scenario) A colleague proposes normalising category to lower case before validating. Do you agree or not, and which tests need to be added?

P06 · Match

Using the table in §6, match each fake reply with the error that classify() must return.

P08 · Multiple choice

The first line of the demo in §8.1 lists the keywords dropped before sending. Which of them does the documentation describe as supported (with limits), so that it is dropped only because of the lab's choice?

P09 · Spot the bug

The stop-reason check below was copied from classify() in lab/classifier.py but has one bug. Find it.

    if response.stop_reason == "refusal":
        return _result(False, error="truncated")
    if response.stop_reason in ("max_tokens", "model_context_window_exceeded"):
        return _result(False, error="truncated")
    if response.stop_reason != "end_turn":
        return _result(False, error="unexpected_stop", details=[str(response.stop_reason)])

P10 · True or false

A characterization test asserts the behaviour that is correct according to the SDK's documentation.

P11 · Recall

Lesson: L1-M05-L01

Lesson L01: which value of priority is valid against {"type": "integer", "minimum": 1, "maximum": 5}?

P12 · Select all that apply

According to §6, what must a bug report for the classifier record? Select every correct option.

P13 · True or false

The lab's fake API rejects every request that the real API rejects.

P15 · Multiple choice

According to the worked example in §4.2, which constraints on priority are checked only by validate() in code?

P16 · True or false

In the try_l02_400.py example in §5.2, the fake returns 400 for the full schema but does not mention pattern, because pattern is supported with limits.

P17 · Match

Match each fake reply with the error that classify() returns (the table in §5.1).

P18 · Spot the bug

Here is a wrong solution to extra exercise §9.1. Find the defect.

def failure_breakdown(api, client, replies):
    counts = {}
    for body, stop in replies:
        try:
            kind = "schema_violation" if validate(json.loads(body)) else "ok"
        except json.JSONDecodeError:
            kind = "invalid_json"
        counts[kind] = counts.get(kind, 0) + 1
    return counts

P19 · Fill in the blank

Of the 10 replies in exercise §9.1, ___ are ok. Among the replies that are not ok, refusals make up a share of ___.

P20 · Apply now

In code-labs/l1-m05, run python -m pytest exercises/test_l02_extra_breakdown.py once untouched, then do extra exercise §9.1 and run it again.

Checklist

11. Summary

  • Concepts: output_config.format; strict tool use; unsupported keywords and the 400 error; two schemas; refusal, max_tokens and enum capitalisation; the behaviour of messages.parse().
  • Skills: testing the request that is sent; testing the six response paths; characterization tests for the SDK.
  • Pitfalls: trusting structured output completely; validating with the stripped schema; parsing before checking the stop reason.
  • You can now: test a structured-output integration end to end without the real API.

12. References

ID Title Publisher URL Accessed Relevance
R1 Structured outputs Anthropic https://platform.claude.com/docs/en/build-with-claude/structured-outputs 2026-10-31 output_config.format, unsupported keywords, SDK, refusal, max_tokens, enum
R2 Strict tool use Anthropic https://platform.claude.com/docs/en/agents-and-tools/tool-use/strict-tool-use 2026-10-31 What strict: true guarantees

Key terms (English ↔ Vietnamese)

English Tiếng Việt
Structured outputs Output có cấu trúc theo schema
Strict tool use Tool có tham số được ràng buộc theo schema
Refusal Model từ chối trả lời
Characterization test Test ghi lại hành vi hiện tại của một thành phần
Constraint Ràng buộc (ví dụ maximum)