Social Media Sentiment Analysis API: Pull the Comments, Score Them Your Way
Social Media Sentiment Analysis API: Pull the Comments, Score Them Your Way
A social media sentiment analysis API does two jobs. It fetches public comment text from platforms like Instagram, TikTok, YouTube, X, and Reddit, and then it labels each comment positive, negative, or neutral. To build one in 2026, pull comments with a read-only data API such as SocialLens, then score them with any LLM using your own rubric.
Key facts
- Sentiment analysis on social media is two jobs: getting the comment text, then scoring it. Scoring is commoditized, and getting the data is the hard part.
- SocialLens returns raw public comments through one endpoint,
GET /v1/post-comments, for 9 platforms: Instagram, TikTok, YouTube, X, Reddit, Facebook, Threads, LinkedIn, and Pinterest. - SocialLens does not compute a sentiment score. You keep the model, the rubric, the language handling, and the aspects.
- A NASA Instagram post read live on 2026-12-04 showed 806,082 likes and 2,691 comments. At 50 comments per call, that is at most 54 paginated requests.
- SocialLens is read-only and public-data-only. It never logs in and never reads DMs, private accounts, or logged-in sessions.
Why is sentiment analysis really two jobs?
Most "sentiment API" pages sell a score. The score is the cheap part. A modern LLM labels "this update broke my login 😡" as negative without fine-tuning, and it handles slang and mixed languages better than the dictionary-based scorers of a few years ago.
The expensive part is getting clean, current, public comment text out of five or more platforms. Each one has its own pagination, rate behavior, page structure, and login walls, and self-maintained scrapers for them tend to break whenever a platform changes its front end.
So split the problem:
| Job | What it involves | Who should own it |
|---|---|---|
| 1. Get the comments | Find posts, paginate threads, normalize fields across platforms, keep data current | A data layer (SocialLens) |
| 2. Score the comments | Label, aspect, confidence, language handling, sarcasm rules | Your model and your rubric |
SocialLens is the comment data layer. Your model is the scoring layer. The rest of this guide builds both, end to end. For the broader picture of feeding social data to agents, see the hub on social media data for AI agents.
Does SocialLens return a sentiment score?
No. SocialLens returns raw public comments (text, author handle, likes, reply count, timestamp) and does not attach a sentiment label. We left scoring out on purpose. A built-in score would lock you into one model, one language strategy, and one definition of "negative," and sentiment definitions vary by team. A support team cares about bug reports, and a brand team cares about tone.
This is also where SocialLens loses if you want a turnkey dashboard. Tools built for marketers ship scores and charts out of the box. SocialLens is for developers who want the data and will write about 60 lines of Python to score it.
How do the three ways to get comment data compare?
You have three realistic options for job 1:
| Approach | Comment coverage | Setup and auth | Maintenance | Main trade-off |
|---|---|---|---|---|
| Official platform APIs (YouTube Data API v3, Meta Graph API, X API, Reddit Data API) | One platform each. Some only return comments on accounts you own or manage | One app review, OAuth flow, and quota system per platform | Low per platform, high across five | Sanctioned and stable, but fragmented. Several platforms restrict comment access to your own content |
| Self-run scrapers and headless browsers | Anything you can render | Proxies, browser fleets, parsers | High. Breaks on front-end changes | Full control, ongoing engineering cost |
| Read-only comment data API (SocialLens) | 9 platforms, one schema, one key | One API key | Handled by the provider | Public data only. No private or owned-account data, no publishing, no built-in score |
When you only need comments on your own YouTube channel, the YouTube Data API v3 is free and official, and you should use it. SocialLens makes more sense once you need public comments on posts you do not own (competitors, creators, news) across several platforms in one format. For the comments endpoint in isolation, read the social media comments API guide.
Which platforms are supported?
The comments endpoint accepts these platform values:
instagram, tiktok, youtube, x, reddit, facebook, threads, linkedin, pinterest
SocialLens covers 17 networks for profile and post reads (adding Telegram, Bluesky, Truth Social, Cosmos, SoundCloud, Kwai, GitHub, and Spotify), but comment pulls are limited to the nine above. If your sentiment project depends on Telegram channel replies, for example, SocialLens is not the right tool today. Reddit threads have their own nuances, which the guide on reading subreddit posts and comments via API covers.
The original data: what one real post costs to analyze
Before writing code, size the job. We read a real public post live through SocialLens: NASA's Instagram post of a globular cluster (instagram.com/p/Df-NlR0PjmN), published 2026-11-20.
Table: Sizing a full-thread sentiment run on one high-engagement post (NASA, Instagram)
| Metric | Value | How it is derived |
|---|---|---|
| Likes | 806,082 | Read live via SocialLens |
| Comments (platform-displayed count) | 2,691 | Read live via SocialLens |
| Comments per 1,000 likes | 3.34 | 2,691 ÷ 806,082 × 1,000 |
| Likes per comment | about 300 (299.6) | 806,082 ÷ 2,691 |
| Days from publish to read | 14 | 2026-11-20 to 2026-12-04 |
| Average comments per day since publish | about 192 | 2,691 ÷ 14 (an average, not a daily curve) |
/post-comments calls at limit=50 |
at most 54 | 53 full pages plus one page of 41 |
| LLM scoring batches at 100 comments each | 27 | 26 full batches plus one batch of 91 |
Data last verified: 2026-12-04
Two takeaways. First, even a post with roughly 800,000 likes has a comment thread small enough to score completely in a few minutes. You do not need to sample. Second, the comment count is a ceiling, not a promise. Platform-displayed counts can include replies, hidden, or removed comments, so the number of comments you actually retrieve may come in lower. Treat 54 as an upper bound on calls.
How do I get Instagram comment sentiment? The four-step pipeline
Here is the full pipeline, using the NASA post as the running example.
Step 1: Find the post(s)
If you already have a post URL, skip this step. Otherwise, list a profile's recent posts with /profile-posts:
curl -s "https://api.sociallens.dev/v1/profile-posts?platform=instagram&username=nasa" \
-H "Authorization: Bearer $SOCIALLENS_API_KEY"
Each post object includes id, url, caption, published_at, likes, views, comments, shares, and likes_hidden. Use comments to pick posts with enough discussion to be worth scoring. Use likes_hidden to know when a like count is unavailable rather than zero. For engagement-side metrics on the same posts, see the social media post metrics API.
Step 2: Pull the comments with pagination
The endpoint:
GET https://api.sociallens.dev/v1/post-comments?platform=PLATFORM&url=POST_URL&limit=50&cursor=CURSOR
Authorization: Bearer YOUR_KEY
The response shape, verified live on 2026-12-04 (comment text and identifiers replaced with placeholders to keep real users anonymous):
{
"exists": true,
"url": "https://www.instagram.com/p/Df-NlR0PjmN/",
"platform": "instagram",
"count": 50,
"total": null,
"has_more": true,
"next_cursor": "...",
"comments": [
{
"id": "...",
"text": "[illustrative] this image is unreal 🔭",
"author": { "username": "...", "name": null, "verified": false },
"likes": 1,
"replies": null,
"published_at": "2026-12-04T06:19:25Z"
}
],
"fetched_at": "...",
"cached": false,
"source_cached": false,
"credits": { }
}
Fields that matter for sentiment work:
has_moreandnext_cursor: keep paging whilehas_moreis true, passingnext_cursorback ascursor.total: can benull. Do not use it as a loop bound. Usehas_more.published_at: needed for trend lines in step 4.likesper comment: lets you weight sentiment by how many people agreed with a comment.cachedandsource_cached: tell you whether you got a fresh read. This matters when you track sentiment over time.credits: what the call consumed. Log it.
The pagination loop:
import os
import requests
API = "https://api.sociallens.dev/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['SOCIALLENS_API_KEY']}"} # sk_live_YOUR_KEY
def fetch_comments(platform: str, url: str, max_comments: int = 3000) -> list[dict]:
comments, cursor = [], None
while len(comments) < max_comments:
params = {"platform": platform, "url": url, "limit": 50}
if cursor:
params["cursor"] = cursor
r = requests.get(f"{API}/post-comments", headers=HEADERS, params=params, timeout=60)
r.raise_for_status()
data = r.json()
if not data.get("exists"):
break # post deleted, private, or URL wrong
comments.extend(data.get("comments", []))
if not data.get("has_more") or not data.get("next_cursor"):
break
cursor = data["next_cursor"]
return comments[:max_comments]
if __name__ == "__main__":
rows = fetch_comments("instagram", "https://www.instagram.com/p/Df-NlR0PjmN/")
print(len(rows), "comments pulled")
Step 3: Score each comment with an LLM
Send comments in batches with a tight rubric, and force structured output so you never have to parse prose. The example uses the official Anthropic Python SDK with tool use, which returns validated JSON matching your schema.
import json
import anthropic
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
RUBRIC = """You label social media comments for sentiment toward the post or brand.
Rules:
- positive: praise, excitement, gratitude, clear approval.
- negative: complaint, anger, disappointment, ridicule, reported bug or problem.
- neutral: questions, tags of friends, off-topic, factual statements, spam.
- Sarcasm: label by the intended meaning, not the literal words.
- Emoji count as signal. Judge any language natively; do not translate first.
- aspect: a 1 to 3 word topic the sentiment is about (e.g. "image quality", "pricing"), or null.
- confidence: 0 to 1.
Return one result per input id."""
TOOL = {
"name": "record_sentiment",
"description": "Record a sentiment label for every comment in the batch.",
"input_schema": {
"type": "object",
"properties": {
"results": {
"type": "array",
"items": {
"type": "object",
"properties": {
"id": {"type": "string"},
"label": {"type": "string", "enum": ["positive", "negative", "neutral"]},
"aspect": {"type": ["string", "null"]},
"confidence": {"type": "number"},
},
"required": ["id", "label", "confidence"],
},
}
},
"required": ["results"],
},
}
def score_batch(comments: list[dict]) -> list[dict]:
payload = [{"id": c["id"], "text": c["text"]} for c in comments if c.get("text")]
if not payload:
return []
msg = client.messages.create(
model="claude-haiku-5-5", # fast and cheap for high volume; any capable model works for this step
max_tokens=8000,
system=RUBRIC,
tools=[TOOL],
tool_choice={"type": "tool", "name": "record_sentiment"},
messages=[{"role": "user", "content": json.dumps(payload, ensure_ascii=False)}],
)
for block in msg.content:
if block.type == "tool_use":
return block.input["results"]
return []
def score_all(comments: list[dict], batch_size: int = 100) -> list[dict]:
scored = []
for i in range(0, len(comments), batch_size):
scored.extend(score_batch(comments[i : i + batch_size]))
return scored
Notice that only id and text go to the model. Usernames stay out of the prompt, which is a cheap privacy win (see the legal section below).
SocialLens is model-agnostic. You can swap in a larger Claude model for nuanced brand work, or a classic transformer sentiment classifier running on your own hardware if cost per comment is the only constraint and your comments are mostly in one language.
Step 4: Aggregate and act
from collections import Counter, defaultdict
def summarize(comments: list[dict], scored: list[dict]) -> dict:
by_id = {c["id"]: c for c in comments}
labels = Counter(s["label"] for s in scored)
daily = defaultdict(Counter)
complaints = Counter()
for s in scored:
c = by_id.get(s["id"])
if not c:
continue
day = (c.get("published_at") or "")[:10]
daily[day][s["label"]] += 1
if s["label"] == "negative" and s.get("aspect"):
complaints[s["aspect"].lower()] += 1 + (c.get("likes") or 0) # weight by agreement
total = sum(labels.values()) or 1
return {
"share": {k: round(v / total, 3) for k, v in labels.items()},
"daily": {d: dict(v) for d, v in sorted(daily.items())},
"top_complaints": complaints.most_common(5),
}
For the NASA post, a run like this might come back around 70% positive, 8% negative, and 22% neutral, with "image quality" as a top positive aspect. That split is illustrative, not a measured result. Sentiment shifts from post to post and from day to day, so run the pipeline yourself rather than citing a number from a blog.
From here, push share to a dashboard, alert when the negative share for a brand crosses a threshold you choose, and send top_complaints to the team that owns the issue. The voice of customer from social media comments guide covers turning these aspects into product feedback.
How many comments can I pull per post?
You get up to 50 per call via limit=50, and you page with next_cursor until has_more is false. SocialLens has no fixed per-post ceiling. In practice you are bounded by what the platform publicly exposes, which can be fewer than the displayed comment count. Set a max_comments cap to control spend on viral posts.
How do I handle sarcasm, emoji, and other languages?
Put the rules in the rubric and let a capable LLM read the original text. Do not translate first, because translation flattens tone. Treat emoji as signal. Label sarcasm by intended meaning. For low-confidence results, route them to a stronger model or a human instead of forcing a label.
Each of these breaks older sentiment tools in a predictable way:
- Sarcasm. "Great, another update that deletes my drafts 🙃" is negative. Lexicon scorers see "great" and call it positive. LLMs get this mostly right, especially with the explicit rule in the rubric. Check
confidence, since sarcasm is where it drops. - Emoji-only comments. "🔥🔥🔥" is positive, "💀" is usually positive amusement in many communities, and "🤡" aimed at a brand is negative. Add community-specific emoji notes to the rubric if your audience uses them in unusual ways.
- Mixed and non-English text. Comments switch languages mid-sentence. Score them natively and, if you report by language, have the model return a language code as an extra field.
- Neutral is not a junk drawer. Tags ("@friend look"), questions ("where was this taken?"), and spam can swamp a thread. Consider splitting neutral into
question,tag, andspamsub-labels. Questions are often the most actionable comments you have. - Aspect-based sentiment. "Love the camera, hate the battery" is both positive and negative. The
aspectfield captures the dominant topic. For finer detail, change the schema to return a list of{aspect, label}pairs per comment.
How do I track sentiment over time?
There are two ways, and they answer different questions:
- Bucket by
published_atwithin one pull. This shows how sentiment evolved on a post since launch (for example, a drop after a controversial reply). - Re-pull on a schedule (daily or weekly) and store each run with its
fetched_at. This shows how a brand's sentiment moves across many posts. Checkcachedandsource_cachedso you know whether a run reflects a fresh read.
Deduplicate by comment id across runs so a long thread is not counted twice. For always-on monitoring across many accounts and keywords, the social listening API guide shows how to combine keyword search with this pipeline. For benchmarking a rival's audience reaction, see competitor content analysis with AI.
Can my AI agent do this without code? Connect the SocialLens MCP server
If you would rather ask Claude "what are people complaining about on NASA's last Instagram post?" than write a script, use the SocialLens MCP server. It runs locally over stdio via npx and exposes read tools. For sentiment work, the relevant ones are get_profile_posts and get_post_comments. The Model Context Protocol is the open standard behind this.
You / your agent
|
v
MCP client (Claude Code, Claude Desktop, Cursor)
| stdio, launched locally via npx
v
SocialLens MCP server (sociallens-mcp)
| ---------------------------------------------
| BOUNDARY: read-only, public data only, no login
| ---------------------------------------------
v
Public posts and comments on supported networks
What an agent can read: public profiles, public posts, public comments on the nine comment-enabled platforms, keyword search results, and transcripts. What it cannot read: DMs, private or friends-only accounts, anything behind a login, or your own account's private analytics. It also cannot post, reply, like, or delete anything.
Get a key at sociallens.dev/keys (register at sociallens.dev/register). Agent docs are at sociallens.dev/agents.
Claude Code
Run one command:
claude mcp add --env SOCIALLENS_API_KEY=sk_live_YOUR_KEY --transport stdio sociallens -- npx -y sociallens-mcp
See the official Claude Code MCP docs for scopes and management commands. The Claude social media data guide has more prompt patterns.
Claude Desktop and Cursor
Both use the same block. For Claude Desktop, edit claude_desktop_config.json. For Cursor, edit .cursor/mcp.json.
{
"mcpServers": {
"sociallens": {
"command": "npx",
"args": ["-y", "sociallens-mcp"],
"env": { "SOCIALLENS_API_KEY": "sk_live_YOUR_KEY" }
}
}
}
Fully quit and reopen the app afterward, then ask something like: "Pull the comments on https://www.instagram.com/p/Df-NlR0PjmN/ and give me a positive, negative, and neutral breakdown with the top three complaint themes."
ChatGPT
Build a Custom GPT and import the OpenAPI file at https://sociallens.dev/openapi.json as an Action, with Bearer authentication set to your key. In your own app, you can also define a function that makes the same GET /v1/post-comments request. There is no remote SocialLens MCP URL to add from a dashboard. The MCP server is local and stdio-only.
Agent frameworks
From any framework that can make HTTP calls, wrap fetch_comments and score_batch above as tools. Frameworks with MCP client support can instead launch npx -y sociallens-mcp as a stdio subprocess with SOCIALLENS_API_KEY in its environment. For how SocialLens compares with other MCP options, see best social media MCP server.
What does it cost?
The SocialLens cost is per read. Each response includes a credits object showing what that call consumed, so you can log real spend per post rather than estimate it. Current rates are on sociallens.dev. The scoring cost is whatever your LLM provider charges per token, and short comments in batches of 100 keep that low.
Budget with the sizing table above. A fully scored 2,691-comment thread is at most 54 comment calls plus 27 model calls. If you need to score hundreds of millions of comments a month, a self-run scraping operation can have lower marginal cost per comment, at the price of the engineering time to keep it running. SocialLens is priced for teams that would rather not run that operation. The unified social media data API page explains how one key and one schema reduce per-platform integration cost.
Is it legal to analyze public social media comments?
Reading publicly available data is generally on firmer ground than accessing gated data. In hiQ Labs v. LinkedIn, the Ninth Circuit held that scraping publicly accessible profiles likely did not violate the federal Computer Fraud and Abuse Act. That case later ended with hiQ found to have breached LinkedIn's user agreement, so platform terms of service remain a separate, real risk.
Comments are also personal data under GDPR and CCPA, even when public. Practical guardrails:
- Keep only what you need. The scoring function above sends only
idandtextto the model. - Report aggregates, not individuals. Do not publish or quote commenters' handles.
- Set a retention period and delete raw comment rows after aggregation.
- Stay read-only. SocialLens never logs in, never touches private accounts, DMs, or logged-in sessions, and cannot write to any platform.
This is not legal advice. Talk to counsel about your jurisdiction and use case.
Troubleshooting
401 or 403 from /post-comments. Your header is missing or malformed. It must be exactly Authorization: Bearer sk_live_.... In MCP setups, a 401 almost always means SOCIALLENS_API_KEY is not in the server's env block. Your shell variables are not inherited by desktop apps.
exists: false. The post was deleted or made private, or the URL is for a different platform than your platform value. Use the canonical post URL, not a share link with tracking parameters.
Loop never ends, or ends early. Loop on has_more and next_cursor, never on total (it can be null). Always pass the latest next_cursor, and keep a max_comments cap as a safety stop.
Retrieved fewer comments than the displayed count. This is expected. Displayed counts can include hidden, removed, or nested replies that are not publicly listed.
MCP server does not appear in Claude Desktop or Cursor.
- Malformed JSON is the top cause. A trailing comma or a missing brace silently disables every server in the file. Validate the file.
- Changes need a full app restart (quit from the menu or tray, not just close the window).
- If
npxis not found, the app is not seeing your shellPATH. Use the absolute path tonpx(find it withwhich npx) ascommand. Relative paths fail because the app's working directory is not your project folder.
Cursor uses the wrong config. Cursor reads both a global ~/.cursor/mcp.json and a project .cursor/mcp.json. If sociallens is defined in both with different keys, you may be running the one you did not expect. Keep it in one place, or give the entries distinct names.
Client only supports remote servers. sociallens-mcp is stdio-only. For clients that cannot launch local processes, use the OpenAPI file or a direct HTTP integration, or put a stdio-to-HTTP bridge you run yourself in front of the server.
The model returns fewer results than comments sent. Lower batch_size to 50, raise max_tokens, and re-score any IDs missing from the output. Empty or media-only comments (no text) are skipped by design.
FAQ
What is a social media sentiment analysis API? It is an API that retrieves public social media comments and classifies their tone as positive, negative, or neutral. With SocialLens, retrieval and scoring are separate: SocialLens returns the raw comments, and your chosen model labels them.
Does SocialLens return a sentiment score? No. It returns raw public comments with text, author handle, likes, replies, and timestamps. Scoring is left to your model on purpose, so you control the rubric, languages, and aspects.
Which platforms can I pull comments from?
Instagram, TikTok, YouTube, X, Reddit, Facebook, Threads, LinkedIn, and Pinterest, using the platform parameter on /v1/post-comments.
How many comments come back per request?
Up to 50 with limit=50. Page with next_cursor while has_more is true. A 2,691-comment post needs at most 54 calls.
Which model should I use for scoring? Any capable LLM works. A fast, inexpensive model like Claude Haiku handles high-volume labeling well. Use a larger model for nuanced brand or sarcasm-heavy work, or a classic transformer classifier for single-language, cost-sensitive jobs.
Can I analyze comments on posts I do not own? Yes, as long as the post and its comments are public. SocialLens reads public data only and never logs in.
Can SocialLens read DMs or private accounts? No. It cannot access DMs, private or friends-only accounts, or logged-in sessions, and it cannot post or reply.
How do I track sentiment over time?
Bucket scored comments by published_at within a thread, and re-pull on a schedule, storing fetched_at per run. Deduplicate by comment id.
Does it work with Claude, Cursor, and ChatGPT?
Yes. Claude Code, Claude Desktop, and Cursor run the local sociallens-mcp server. ChatGPT uses a Custom GPT that imports https://sociallens.dev/openapi.json.
Is analyzing public comments legal? Reading public data is generally lower risk, but platform terms and privacy laws like GDPR and CCPA still apply. Minimize personal data and report aggregates. This is not legal advice.
SocialLens is the comment data layer, and your model is the scoring layer. Get a key at sociallens.dev/keys, point fetch_comments at a post you care about, and have a sentiment breakdown in under 100 lines of Python. To extend this into creator and account-level analysis, continue with social media profile analysis with an AI agent.
Related guides
- Social Media APIs Compared: Official APIs vs One Public Data API
- Social Media Comments API: Read the Comments on Any Public Post by URL
- How to Get Likes, Views and Comments for Any Post by URL
- Build a LangChain Tool for Live Social Media Data (Followers, Posts, Comments)
- Voice of Customer from Social Media Comments with AI (2026)
- How to Give AI Agents Live Social Media Data (MCP and API Guide for Claude, ChatGPT and Cursor)
- Social Media Analytics API: One Schema, 17 Networks