← Back to Blog

Sentiment Analysis API: Complete Tutorial

tutorialaiapisentimentanalysis

Sentiment Analysis API Tutorial: Classify Text Sentiment in Minutes

Understanding how your customers feel about your product, brand, or service is one of the most valuable things you can do with text data. Whether you’re processing thousands of support tickets or monitoring social media mentions, a sentiment analysis API makes it practical to do this at scale — without building a machine learning model from scratch.

This sentiment analysis API tutorial walks you through everything you need to get started: what the API does, how to call it, and how to integrate it into a real workflow.


What Is Sentiment Analysis and Why Does It Matter?

Sentiment analysis (sometimes called opinion mining) is the process of automatically identifying whether a piece of text expresses a positive, negative, or neutral opinion. It’s a core task in natural language processing (NLP) and has become a standard tool in modern data pipelines.

Common use cases include:

  • Customer feedback analysis — Automatically categorizing support tickets, reviews, or survey responses
  • Brand monitoring — Tracking public sentiment around product launches or announcements
  • Market research — Aggregating opinions from forums, news, or social platforms
  • Content moderation — Flagging hostile or negative content before it’s published

If you’re already working with AI-powered document workflows — for example, extracting structured data from files like invoices or receipts (see our related posts: “How to Extract Invoice Data from PDFs Using AI” and “Parse Receipts Automatically with AI API”) — adding sentiment analysis is a natural next step for building richer, more intelligent pipelines.


How the Today’s World Sentiment Analysis API Works

The Today’s World API provides a straightforward REST endpoint for text sentiment classification. You send it a string of text, and it returns a sentiment label (positive, negative, or neutral) along with a confidence score and, optionally, a breakdown by sentence or aspect.

The API is built on a fine-tuned NLP model that handles a wide range of text types — from terse one-line reviews to multi-paragraph customer emails.

Before making your first call, get started by creating a free account and grabbing your API key from the dashboard.


Making Your First Sentiment Analysis API Call

The Endpoint

The sentiment endpoint accepts a POST request with a JSON body containing the text you want to analyze.

curl -X POST https://api.todaysworld.com/v1/sentiment/analyze \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{
    "text": "The onboarding experience was smooth and the support team was incredibly helpful.",
    "language": "en",
    "granularity": "document"
  }'

Understanding the Request Body

FieldTypeRequiredDescription
textstringYesThe text to analyze (up to 5,000 characters)
languagestringNoLanguage code (default: "en")
granularitystringNo"document" for overall score, "sentence" for per-sentence breakdown

Sample Response

{
  "status": "success",
  "sentiment": "positive",
  "confidence": 0.94,
  "scores": {
    "positive": 0.94,
    "neutral": 0.04,
    "negative": 0.02
  },
  "language_detected": "en"
}

The confidence score tells you how certain the model is about its classification. Scores above 0.80 are generally reliable for automated decision-making. For borderline cases (say, confidence between 0.50 and 0.70), you may want to route text to a human reviewer.


Using the Sentiment Analysis API with Python

If you’re building a NLP sentiment Python integration, here’s a minimal working example using the requests library.

Installation

pip install requests

Basic Python Integration

import requests

API_KEY = "YOUR_API_KEY"
ENDPOINT = "https://api.todaysworld.com/v1/sentiment/analyze"

def analyze_sentiment(text: str) -> dict:
    headers = {
        "Content-Type": "application/json",
        "x-api-key": API_KEY
    }
    payload = {
        "text": text,
        "language": "en",
        "granularity": "document"
    }
    response = requests.post(ENDPOINT, json=payload, headers=headers)
    response.raise_for_status()
    return response.json()

# Example usage
result = analyze_sentiment("The new dashboard update is confusing and slow.")
print(f"Sentiment: {result['sentiment']}")
print(f"Confidence: {result['confidence']}")

Analyzing Multiple Texts in Bulk

For a customer feedback analysis API workflow, you’ll typically want to process many inputs at once. Here’s a simple loop that reads from a list:

feedback_samples = [
    "Absolutely love the new features!",
    "Shipping took three weeks. Very disappointed.",
    "Product is okay, nothing special.",
    "Best purchase I've made this year.",
    "The app crashed twice during setup."
]

for text in feedback_samples:
    result = analyze_sentiment(text)
    label = result["sentiment"]
    score = result["confidence"]
    print(f"[{label.upper()} | {score:.2f}] {text}")

Output:

[POSITIVE | 0.97] Absolutely love the new features!
[NEGATIVE | 0.91] Shipping took three weeks. Very disappointed.
[NEUTRAL  | 0.78] Product is okay, nothing special.
[POSITIVE | 0.96] Best purchase I've made this year.
[NEGATIVE | 0.88] The app crashed twice during setup.

This kind of loop is easy to adapt for reading from a CSV, a database query, or a live API feed.


Sentence-Level Sentiment Breakdown

For longer texts — like multi-paragraph reviews or support emails — document-level scoring can miss nuance. A customer might praise your product but criticize your billing process in the same message.

Setting "granularity": "sentence" breaks the analysis down by individual sentence:

curl -X POST https://api.todaysworld.com/v1/sentiment/analyze \
  -H "Content-Type: application/json" \
  -H "x-api-key: YOUR_API_KEY" \
  -d '{
    "text": "The product quality is excellent. However, the delivery was delayed by a week. Customer support resolved my issue quickly.",
    "language": "en",
    "granularity": "sentence"
  }'

The response will include a sentences array with individual scores, letting you pinpoint exactly which parts of the feedback are positive or negative — a major advantage when using this as an opinion mining API for detailed customer research.


Handling Errors Gracefully

The API uses standard HTTP status codes. Here are the ones you’re most likely to encounter:

CodeMeaningWhat to Do
200SuccessProcess the response normally
400Bad requestCheck your JSON body for missing or malformed fields
401UnauthorizedVerify your API key is correct and active
429Rate limit exceededAdd retry logic with exponential backoff
500Server errorRetry after a short delay; contact support if persistent

A robust Python integration should always include a try/except block around the API call and handle 429 responses with a backoff strategy.


Tips for Getting Better Results

  • Clean your text first. Remove HTML tags, excessive punctuation, and encoding artifacts before sending. Noisy input leads to lower confidence scores.
  • Match granularity to your use case. Use "document" for short reviews and "sentence" for emails or long-form feedback.
  • Use the confidence score. Don’t treat every classification as equally reliable. Set a threshold (e.g., 0.75) below which you flag results for manual review.
  • Batch intelligently. If you’re processing thousands of records, consider parallelizing requests with concurrent.futures to stay within rate limits while maximizing throughput.

For full parameter documentation and advanced options like aspect-based sentiment targeting, check the API docs.


What to Build Next

Once you have sentiment classification working, there are several directions to extend your pipeline:

  • Trend dashboards — Plot sentiment over time to detect shifts after product releases or policy changes
  • Automated routing — Send negative-sentiment tickets directly to a priority support queue
  • Aggregated reporting — Score and summarize feedback by product category, region, or customer segment

The Today’s World API is designed to fit into existing workflows without heavy lifting — whether you’re connecting to a CRM, a data warehouse, or a simple spreadsheet.


Ready to automate your workflow? Try it free at todaysworld.com/try or get API access on RapidAPI.