Claude API Sentiment Analysis Tutorial Guide
What you'll build
This guide shows you how to use the Claude API to classify text sentiment — positive, negative, neutral, or a finer-grained scale — and return it as structured data your application can use directly. You'll see working prompt templates, a JSON output format, a batching strategy for processing large volumes of text, and code you can copy into a Node.js or Python project today.
If you just need the fastest path: send the text to Claude with a system prompt that defines the sentiment categories and output format, force JSON output, and parse the result. Everything below explains how to do that reliably in production, not just in a one-off script.
Why use an LLM instead of a traditional sentiment classifier
Rule-based and classic ML sentiment models (VADER, TextBlob, fine-tuned BERT models) are fast and cheap but struggle with sarcasm, mixed sentiment, domain-specific language, and context that spans multiple sentences. Claude handles all of these better because it actually reads the text rather than scoring keyword frequency. You also get this for free:
- Reasoning about context: "The delivery was fast but the product broke in two days" correctly scores as mixed/negative, not neutral.
- Custom categories: you're not locked into positive/negative/neutral — ask for urgency, emotion, or intent in the same call.
- No training data required: you define categories in the prompt instead of labeling thousands of examples.
The tradeoff is cost and latency per request compared to a local model, so for very high-volume, low-stakes classification, a traditional model might still be the right tool. For support tickets, reviews, survey responses, and social media monitoring where nuance matters, Claude is usually worth it.
Designing the prompt
The key to reliable sentiment analysis with Claude is constraining the output format. Don't ask for a free-text explanation if you're going to parse it programmatically — ask for JSON.
You are a sentiment analysis engine. Classify the sentiment of the
user-provided text and respond with ONLY valid JSON in this exact shape:
{
"sentiment": "positive" | "negative" | "neutral" | "mixed",
"confidence": 0.0-1.0,
"reasoning": "one short sentence"
}
Do not include markdown formatting, code fences, or any text outside the JSON object.
Put this in the system prompt, and send the text to analyze as the user message. Keeping the instructions in the system prompt means you can reuse the same request structure across thousands of calls and just swap the input text.
Example request
Here's a working example using curl against the Claude API directly:
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-5",
"max_tokens": 200,
"system": "You are a sentiment analysis engine. Respond with ONLY valid JSON: {\"sentiment\": \"positive|negative|neutral|mixed\", \"confidence\": 0.0-1.0, \"reasoning\": \"one short sentence\"}",
"messages": [
{"role": "user", "content": "The support team resolved my issue fast, but I had to wait 40 minutes to even get connected."}
]
}'
Expected response content:
{
"sentiment": "mixed",
"confidence": 0.82,
"reasoning": "Fast resolution is positive but the long wait time is a clear negative."
}
Batching text for higher throughput
Calling the API once per review or ticket works, but if you're processing large batches, send multiple items in a single request and ask for an array back. This cuts round trips significantly.
{
"model": "claude-sonnet-4-5",
"max_tokens": 1000,
"system": "Classify sentiment for each numbered item. Return ONLY a JSON array where each element is {\"id\": number, \"sentiment\": \"positive|negative|neutral|mixed\", \"confidence\": 0.0-1.0}.",
"messages": [
{
"role": "user",
"content": "1. Loved the new update, much faster.\n2. App crashes every time I open it.\n3. It's fine, does what it says."
}
]
}
Keep batches to a reasonable size (10-30 items depending on text length) so you stay well under the max output tokens and the model doesn't start dropping items. Always validate that the array length matches your input count before trusting the result.
Handling edge cases
A few things to build into your pipeline rather than discover in production:
- Empty or near-empty text: define what "neutral" means for empty strings, or filter them out before sending.
- Multiple languages: Claude handles multilingual text well, but specify in the prompt whether you want sentiment relative to the source language's tone or a normalized scale.
- Non-JSON output: even with strict instructions, occasionally wrap the parse in a try/catch and retry once with a stricter reminder appended to the prompt.
- Long documents: for anything beyond a few paragraphs, summarize sentiment per section rather than asking for one label across the whole document.
Running this through SubToAPI
If your team is already using Claude through a shared Anthropic account, routing sentiment analysis calls through SubToAPI gives you a clean HTTPS endpoint with per-application API keys instead of sharing one raw credential across services. That matters once sentiment analysis moves from a prototype script into a production pipeline feeding a dashboard or alerting system — you get usage metadata per key so you can see exactly how much volume your sentiment classifier is consuming versus other features, plus streaming support if you want to show results as they're generated.
Setup looks like this once you've created a key in the dashboard:
const response = await fetch("https://api.subtoapi.app/v1/messages", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.SUBTOAPI_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
model: "claude-sonnet-4-5",
max_tokens: 200,
system: "You are a sentiment analysis engine. Respond with ONLY valid JSON.",
messages: [{ role: "user", content: reviewText }],
}),
});
See the quickstart and the messages endpoint docs for the full request/response reference, and pricing for plan details if you're scaling this across a team.
questions
Does Claude return a confidence score for sentiment automatically? No — Claude doesn't have a built-in sentiment score. You get a confidence value by explicitly asking for one in the prompt, and it reflects the model's own self-assessed certainty rather than a calibrated statistical probability.
Can Claude detect sarcasm in sentiment analysis? Generally yes, much better than keyword-based classifiers, because it reads full context. It's not infallible on very subtle or culturally specific sarcasm, so spot-check results on ambiguous categories like "mixed" sentiment.
How much does running sentiment analysis at scale cost? Cost depends on input/output tokens per request and your chosen Claude model. Batching multiple texts into one request and keeping responses short (just the JSON) reduces cost significantly compared to one call per item with verbose output.