Building with AI APIs · ProLesson 2 of 6 · 10 min
Get reliable JSON with structured outputs
Stop parsing paragraphs. Define a schema, get data your code can trust, and handle the cases where the model can't comply.
When AI output feeds into your code (a database, a dashboard, another API), you need data, not prose. Asking nicely for JSON works most of the time, which in production means it breaks sometimes. Structured outputs constrain the response to a schema you define, so you get valid, typed data back.
extract-invoice.ts
import Anthropic from '@anthropic-ai/sdk';
import { betaZodOutputFormat } from '@anthropic-ai/sdk/helpers/beta/zod';
import { z } from 'zod';
const Invoice = z.object({
vendor: z.string(),
total: z.number().describe('Total amount due, as a number'),
currency: z.string().describe('Three-letter code, e.g. USD'),
due_date: z.string().describe('YYYY-MM-DD, or an empty string if not stated'),
});
const client = new Anthropic();
const res = await client.beta.messages.parse({
model: 'claude-sonnet-5-5',
max_tokens: 1000,
output_config: { format: betaZodOutputFormat(Invoice) },
messages: [{ role: 'user', content: `Extract the invoice details:\n\n${invoiceText}` }],
});
if (res.stop_reason === 'refusal' || !res.parsed_output) {
throw new Error('Could not extract this invoice'); // send to a human
}
const invoice = res.parsed_output; // typed: invoice.total is a numberDesign the schema like an API
Unlock the rest of this lesson with Pro
In this lesson
- Design the schema like an API
- Always handle the failure path
- Hands-on practice with personal feedback from Arvid
- A quick quiz to check what you learned
Unlock this lesson and every lesson in the Foundations, Advanced and Expert levels and all courses, plus certificates and a monthly allowance of AI practice, for $12/month.
Start free, upgrade anytime
Already have an account? Log in