SOP: Enforce Structured Outputs ​
Updated: 2026-05-26
Force Claude to return valid JSON matching a specific schema, with no extra text.
Prerequisites ​
- Messages API integration working
- JSON Schema for your desired output format
Steps ​
Step 1: Define Your Output Schema ​
python
response_format = {
"type": "json_schema",
"name": "sentiment_analysis",
"schema": {
"type": "object",
"properties": {
"sentiment": {"type": "string", "enum": ["positive", "negative", "neutral"]},
"confidence": {"type": "number", "minimum": 0, "maximum": 1},
"key_phrases": {"type": "array", "items": {"type": "string"}}
},
"required": ["sentiment", "confidence", "key_phrases"]
}
}Step 2: Send Request with Response Format ​
bash
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-6",
"max_tokens": 1024,
"messages": [
{"role": "user", "content": "Analyze: The product exceeded our expectations"}
],
"response_format": {
"type": "json_schema",
"name": "sentiment_analysis",
"schema": {
"type": "object",
"properties": {
"sentiment": {"type": "string", "enum": ["positive", "negative", "neutral"]},
"confidence": {"type": "number"},
"key_phrases": {"type": "array", "items": {"type": "string"}}
},
"required": ["sentiment", "confidence", "key_phrases"]
}
}
}'Step 3: Parse and Validate ​
The response will contain only JSON text. Parse and validate against your schema:
python
import json
response_text = response.content[0].text
parsed = json.loads(response_text)
assert "sentiment" in parsed
assert parsed["sentiment"] in ["positive", "negative", "neutral"]Verification Checklist ​
- [ ] Response is parseable JSON (no markdown wrapper, no preamble)
- [ ] All required fields present
- [ ] Enum values match allowed options
- [ ] No extra text outside the JSON object