How to get structured output from Claude API
Quick answer
Use the
anthropic.Anthropic client with the messages.create method, instructing Claude via the system prompt to respond in JSON or a structured format. Parse the returned response.content[0].text as JSON to get structured output.PREREQUISITES
Python 3.8+Anthropic API keypip install anthropic>=0.20
Setup
Install the official Anthropic Python SDK and set your API key as an environment variable.
- Run
pip install anthropicto install the SDK. - Set your API key in your shell:
export ANTHROPIC_API_KEY='your_api_key_here'.
pip install anthropic Step by step
Use the Anthropic client to send a prompt instructing Claude to respond with JSON. Then parse the response text as JSON.
import os
import json
from anthropic import Anthropic
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
system_prompt = (
"You are a helpful assistant that responds ONLY with JSON objects. "
"Given a user query, output a JSON with keys 'summary' and 'keywords'."
)
user_message = "Summarize the benefits of AI in healthcare."
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=500,
system=system_prompt,
messages=[{"role": "user", "content": user_message}]
)
text_response = response.content[0].text
try:
structured_output = json.loads(text_response)
print("Structured output:", structured_output)
except json.JSONDecodeError:
print("Failed to parse JSON. Raw response:", text_response) output
Structured output: {'summary': 'AI improves healthcare by enabling faster diagnosis, personalized treatment, and better patient outcomes.', 'keywords': ['AI', 'healthcare', 'diagnosis', 'personalized treatment', 'patient outcomes']} Common variations
You can customize the structured output format by changing the system prompt instructions. Use other Claude models like claude-opus-4 for different capabilities. For async usage, use Python's asyncio with the Anthropic SDK's async client methods.
import asyncio
import os
import json
from anthropic import Anthropic
async def main():
client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])
system_prompt = (
"You are a helpful assistant that responds ONLY with JSON objects. "
"Output a JSON with keys 'title' and 'points'."
)
user_message = "List key advantages of electric vehicles."
response = await client.messages.acreate(
model="claude-opus-4",
max_tokens=300,
system=system_prompt,
messages=[{"role": "user", "content": user_message}]
)
text_response = response.content[0].text
try:
structured_output = json.loads(text_response)
print("Structured output:", structured_output)
except json.JSONDecodeError:
print("Failed to parse JSON. Raw response:", text_response)
asyncio.run(main()) output
Structured output: {'title': 'Advantages of Electric Vehicles', 'points': ['Environmentally friendly', 'Lower operating costs', 'Reduced noise pollution', 'Energy efficiency']} Troubleshooting
- If JSON parsing fails, verify the
systemprompt clearly instructs Claude to respond only with JSON. - Use explicit delimiters like triple backticks
```json ... ```in the prompt to help Claude format output. - Check for trailing text or explanations outside the JSON and trim before parsing.
Key Takeaways
- Use the
systemprompt to instruct Claude to respond with JSON for structured output. - Parse
response.content[0].textas JSON to extract structured data. - Use explicit formatting hints like JSON code blocks in prompts to improve output reliability.