Claude API - Structured Output
작성 일자 : 2026년 07월 19일
Structured Output
Structured Outputs는 Claude의 응답을 내가 정의한 JSON Schema에 강제로 맞추는 기능이다. "JSON으로만 답해줘"라고 프롬프트에 쓰는 게 아니라, API 레벨에서 constrained decoding(문법 제약 샘플링)으로 스키마에 맞는 토큰만 생성하게 만든다.
왜 쓰는가
프롬프트만으로 JSON을 받으면 이런 일이 생긴다:
- 앞뒤에 "물론이죠! 다음은 JSON입니다:" 같은 잡담이 붙음
- 마크다운 코드펜스(```json)로 감싸서 옴
- 필수 필드 누락, 타입 불일치
- 결국 JSON.parse() 에러 → 재시도 로직 필요
Structured Outputs를 쓰면 항상 유효한 JSON, 항상 스키마 준수가 보장된다. 파싱 에러 핸들링과 재시도 코드를 걷어낼 수 있다.
Structured Outputs 사용법
curl https://api.anthropic.com/v1/messages \
-H "content-type: application/json" \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-d '{
"model": "claude-sonnet-4-6",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": "이메일에서 정보 추출: 김민수(minsu@example.com)님이 Enterprise 플랜에 관심 있고 다음 주 화요일 오후 2시 데모를 원함"
}
],
"output_config": {
"format": {
"type": "json_schema",
"schema": {
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string"},
"plan_interest": {"type": "string"},
"demo_requested": {"type": "boolean"}
},
"required": ["name", "email", "plan_interest", "demo_requested"],
"additionalProperties": false
}
}
}
}'
{
"name": "김민수",
"email": "minsu@example.com",
"plan_interest": "Enterprise",
"demo_requested": true
}
알아둘 것
- 첫 요청은 느리다 — 스키마를 문법으로 컴파일하는 시간이 추가됨. 컴파일 결과는 24시간 캐싱되어 이후 요청은 빠르다.
- 토큰 비용 — 스키마 설명용 시스템 프롬프트가 자동 주입되어 입력 토큰이 약간 늘어난다.
- 스키마 제약 — minimum, maxLength 같은 일부 JSON Schema 기능은 미지원. Python(Pydantic)/TypeScript(Zod) SDK를 쓰면 자동 변환 + 클라이언트 측 검증까지 해준다.
- 예외 상황 — 안전상 거부(stop_reason: "refusal")나 max_tokens 도달 시에는 스키마와 다른 출력이 나올 수 있으니 이 두 케이스는 체크할 것.
- 호환성 — prefill, citations와는 같이 못 쓴다. 스트리밍·배치 처리는 지원.
Structured outputs
Get validated JSON results from agent workflows
platform.claude.com