A Reddit thread is not a list of opinions. It is a tree. A top comment gets 700 points, the first reply disagrees, a reply to that reply sides with the top comment, and the mood changes as you go deeper. If you flatten the thread and score every comment the same, you lose that structure before the analysis starts.
This guide pulls a post with its nested comments from the SteadyAPI Reddit API, flattens the tree into rows that keep each comment's parent and depth, cleans the text, and runs a first sentiment pass. The output is a CSV you can feed to any NLP library or LLM.
Prerequisites
- A SteadyAPI API key from steadyapi.com. One thread costs 1 request.
- Python 3.8+ with
requests. The sentiment step uses plain Python, so you can swap in your own model later.
One call returns the post and its tree
GET /v1/reddit/post (weight 1) takes the full post URL as url. The response has the post in body.post and the comments in body.post_comments. Each comment has id, author, score, up_votes, created_utc, content, and a replies list that holds the same structure again.
Here is a trimmed response with usernames replaced:
{
"meta": { "version": "v1.0", "status": 200, "totalComments": 40 },
"body": {
"post": { "title": "What's the biggest cult hiding in plain sight ...", "score": 3291, "num_comments": 3012 },
"post_comments": [
{
"id": "19szd95zxhukj",
"author": "user_a",
"score": 30,
"created_utc": 1795284685,
"content": "religion ",
"replies": [
{
"id": "19szdfhxvfg1u",
"author": "user_b",
"score": -11,
"content": "Religion actually had a place thousands of years ago ...",
"replies": [
{ "id": "19szoe8buzv29", "author": "user_c", "score": 7, "content": "Cults are just less established religions", "replies": [] }
]
}
]
}
]
}
}
Note the negative score on the reply. Votes are part of the signal, so keep them.
What the tree does not give you
Plan around these limits before you promise "all the comments":
- A response holds a slice of the thread. In my tests, every large thread returned 40 comments in
meta.totalComments, from a thread Reddit counts at 3,012 down to one counted at 129. Smaller threads came back almost whole: 7 comments in the post, 6 in the response. - You cannot choose the slice. There is no parameter for sorting or paging comments, and the top-level comments were not in score order in my tests. Treat results as a sample of the discussion, not a census.
- Some threads fail. A few popular threads returned HTTP 200 with
"success": falseandPlease enter a valid subReddit URL.even though the URLs were valid. Retrying did not help for those. Skip and log them. likesis an empty string. Usescoreand ignorelikes.
From nested replies to flat rows
Sentiment tools and spreadsheets want one row per comment. The flatten function in the script below walks the tree recursively and carries the parent id and depth with each comment. With parent_id you can rebuild the tree in pandas or a graph library. With depth you can ask whether replies are more negative than top-level comments.
The full script
The script fetches one thread, flattens it, cleans the text, labels each comment, writes a CSV, and prints three views: overall, weighted by score, and by depth. The label comes from a tiny word list so you can run it with no extra packages. It is a baseline, and score_text() is the one function to replace with VADER, a transformer model, or an LLM call.
import csv
import html
import os
import re
import sys
import time
from collections import Counter, defaultdict
import requests
BASE = "https://api.steadyapi.com"
API = f"{BASE}/v1/reddit"
HEADERS = {"Authorization": f"Bearer {os.environ['STEADYAPI_KEY']}"}
# A tiny baseline lexicon. Swap score_text() for VADER or an LLM when you are ready.
POSITIVE = {"good", "great", "love", "loved", "awesome", "amazing", "best", "helpful", "useful",
"nice", "excellent", "agree", "thanks", "happy", "works", "better", "fun", "easy"}
NEGATIVE = {"bad", "terrible", "hate", "hated", "awful", "worst", "useless", "broken", "wrong",
"scam", "annoying", "disagree", "sad", "worse", "slow", "hard", "problem", "cult"}
def fetch_thread(url):
for attempt in range(3):
r = requests.get(f"{API}/post", headers=HEADERS, params={"url": url}, timeout=90)
if r.status_code in (429, 500, 502, 503):
time.sleep(2 ** attempt)
continue
r.raise_for_status()
data = r.json()
if data.get("success") is False:
raise ValueError(data["message"])
return data
raise RuntimeError("thread request failed after retries")
def flatten(comments, parent_id=None, depth=0):
"""Turn the nested replies into one row per comment, keeping parent and depth."""
for c in comments:
yield {
"id": c["id"],
"parent_id": parent_id,
"depth": depth,
"author": c["author"],
"score": c["score"] if isinstance(c["score"], int) else 0,
"created_utc": c["created_utc"],
"text": c["content"],
}
yield from flatten(c["replies"], c["id"], depth + 1)
def clean(text):
text = html.unescape(text)
text = re.sub(r"https?://\S+", "", text)
return re.sub(r"\s+", " ", text).strip()
def score_text(text):
words = re.findall(r"[a-z']+", text.lower())
pos = sum(w in POSITIVE for w in words)
neg = sum(w in NEGATIVE for w in words)
return "positive" if pos > neg else "negative" if neg > pos else "neutral"
def analyze(url, out="comments.csv"):
data = fetch_thread(url)
post = data["body"]["post"]
rows = []
for row in flatten(data["body"]["post_comments"]):
row["text"] = clean(row["text"])
if row["text"] in ("", "[deleted]", "[removed]"):
continue
row["label"] = score_text(row["text"])
rows.append(row)
with open(out, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
print(post["title"])
print(f"post score {post['score']:,}, reddit says {post['num_comments']:,} comments, "
f"API returned {data['meta']['totalComments']} ({len(rows)} usable)")
counts = Counter(r["label"] for r in rows)
print("overall:", ", ".join(f"{k} {v / len(rows):.0%}" for k, v in counts.most_common()))
weight = defaultdict(float)
for r in rows:
weight[r["label"]] += max(r["score"], 1)
total = sum(weight.values())
print("score-weighted:", ", ".join(f"{k} {v / total:.0%}" for k, v in sorted(weight.items(), key=lambda x: -x[1])))
by_depth = defaultdict(Counter)
for r in rows:
by_depth[r["depth"]][r["label"]] += 1
for depth in sorted(by_depth):
n = sum(by_depth[depth].values())
neg = by_depth[depth]["negative"] / n
print(f"depth {depth}: {n:>2} comments, {neg:.0%} negative")
if __name__ == "__main__":
analyze(sys.argv[1])
Run it with STEADYAPI_KEY=your_key python tree.py POST_URL. This is real output for a thread in r/Python:
For devs using Claude Code or similar at work: what's the 10% you still fix by hand in Python?
post score 68, reddit says 129 comments, API returned 40 (40 usable)
overall: neutral 65%, positive 28%, negative 8%
score-weighted: neutral 47%, positive 31%, negative 21%
depth 0: 7 comments, 14% negative
depth 1: 11 comments, 18% negative
depth 2: 10 comments, 0% negative
depth 3: 7 comments, 0% negative
depth 4: 5 comments, 0% negative
Reading the numbers
The weighted view moved negative from 8% to 21%, because the few comments the word list marked negative had more points than the typical comment. That gap is the reason to keep scores. A flat count says the thread is mostly neutral. The weighted count says the comments people voted up leaned more critical.
Do not over-read the baseline. A word list misses sarcasm, negation and anything it does not know, and 65% neutral is mostly a sign of how small the lexicon is. Use it to check the pipeline, then replace score_text(). The CSV already has text, score, depth and parent for a better model.
Best practices for sentiment work on threads
- Label in context. A reply of "Same" means nothing alone. With
parent_id, send the parent text along with the reply. - Keep the thread snapshot. Scores change. Save the CSV with the fetch time so you can compare later.
- Poll sparingly. Responses are cached for about 15 minutes, and each thread is 1 request. The Free plan's 500 requests a month covers 500 threads. The Starter plan ($14.99/mo, 10,000 requests) covers 10,000. The standard rate limit is 10 requests per second, and only HTTP 200 responses count toward your quota.
Bonus: ask about a thread directly
If you use Claude Code, Cursor, VS Code, or any MCP client, you can connect it to https://api.steadyapi.com/mcp with your API key. Then you can ask what a thread's comments think in plain English, before you write the pipeline.
Conclusion
You fetched a thread, flattened its reply tree into rows with parent and depth, cleaned the text, and produced a first sentiment breakdown that respects votes and depth. The same CSV works with any classifier you plug in.
Create a free account at steadyapi.com (no card required) and run the script on a thread in your field. The API documentation lists every Reddit parameter with ready-made examples in cURL, JavaScript, PHP, and Python.