Reddit's own pages are not an archive. Posts scroll off, titles get edited, scores move, and some posts are removed. If you want to study a community over time, you need your own copy: a table with one row per post that you update as you go.
This guide builds that table. A short script pages through a subreddit's newest posts with SteadyAPI's Reddit API, classifies each post as text, image, gallery, video or link, and saves it to SQLite. Run it on a schedule and it stops as soon as it reaches posts it already holds. You get the script in PHP and in Node.js. Both were tested and do the same thing.
Prerequisites
- A SteadyAPI API key from steadyapi.com. A full run costs at most 8 requests, and a catch-up run costs 2.
- PHP 8.1+ with the
curlandpdo_sqliteextensions, or Node.js 22.13+. The Node version uses the built-innode:sqlitemodule, so it needs no packages. I tested it on Node 22.23, where it prints an experimental warning. SQLite itself needs no server.
How paging works
GET /v1/reddit/posts (weight 2) takes a subreddit, a sortType of new, hot, top or rising, and a cursor. For an archive, use sortType=new:
- A page holds 25 posts. The response has
meta.cursor, a post name such ast3_1y1r83v. Send it back ascursorto get the next page. I fetched two consecutive pages and no post appeared in both. - Pinned posts come first. On page 1, posts with
stickiedset are old moderator posts. The script skips them, which is why a page often saves 24 posts, not 25. - Titles contain HTML entities, such as
&. The script decodes them before saving. - Each post has what you need for metadata:
id,title,author,score,num_comments,upvote_ratio,created_utc,permalink,url,domain,is_video,is_selfandover_18.
The schema and the rules
One row per post, keyed by Reddit's post id. The script does three things worth knowing about:
- Upsert. If the post exists, it updates
score,num_comments,upvote_ratioandlast_seen, and leaves the rest alone.first_seenrecords when you first saved it. - Stop when caught up. A page with zero new posts means everything older is already in the table, so the script stops. That keeps scheduled runs cheap.
- Media type.
is_videomakes itvideo. A/gallery/URL makes itgallery. A direct image URL, or thei.redd.itdomain, makes itimage. Self posts aretext, and everything else islink.
The PHP script
Save this as reddit_archive.php:
<?php
$base = 'https://api.steadyapi.com';
$key = getenv('STEADYAPI_KEY');
$subreddit = $argv[1] ?? 'learnpython';
$maxPages = 4;
$db = new PDO('sqlite:reddit_archive.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec('CREATE TABLE IF NOT EXISTS posts (
id TEXT PRIMARY KEY,
subreddit TEXT, title TEXT, author TEXT,
score INTEGER, num_comments INTEGER, upvote_ratio REAL,
created_utc INTEGER, permalink TEXT, url TEXT,
media_type TEXT, over_18 INTEGER,
first_seen INTEGER, last_seen INTEGER
)');
function call(string $url, string $key): array
{
$failures = 0;
for ($attempt = 0; $attempt < 4; $attempt++) {
$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 90,
CURLOPT_HTTPHEADER => ["Authorization: Bearer $key"],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if (in_array($status, [429, 500, 502, 503], true) || $body === false) {
sleep(2 ** $attempt);
continue;
}
$data = json_decode($body, true);
if ($status !== 200 || !is_array($data)) {
throw new RuntimeException("HTTP $status");
}
if (($data['success'] ?? true) === false) {
if (++$failures < 2) {
sleep(2); // some requests fail once and then work, so retry one time
continue;
}
throw new RuntimeException($data['message'] ?? 'request failed');
}
return $data;
}
throw new RuntimeException('request failed after retries');
}
function mediaType(array $p): string
{
$url = $p['url'] ?? '';
if (!empty($p['is_video'])) return 'video';
if (str_contains($url, '/gallery/')) return 'gallery';
if (preg_match('/\.(jpe?g|png|gif|webp)(\?|$)/i', $url) || ($p['domain'] ?? '') === 'i.redd.it') return 'image';
return !empty($p['is_self']) ? 'text' : 'link';
}
$upsert = $db->prepare('INSERT INTO posts
(id, subreddit, title, author, score, num_comments, upvote_ratio, created_utc, permalink, url, media_type, over_18, first_seen, last_seen)
VALUES (:id, :subreddit, :title, :author, :score, :num_comments, :upvote_ratio, :created_utc, :permalink, :url, :media_type, :over_18, :now, :now)
ON CONFLICT(id) DO UPDATE SET score = :score, num_comments = :num_comments, upvote_ratio = :upvote_ratio, last_seen = :now');
$exists = $db->prepare('SELECT 1 FROM posts WHERE id = ?');
$cursor = null;
$added = 0;
$updated = 0;
for ($page = 1; $page <= $maxPages; $page++) {
$query = ['subreddit' => $subreddit, 'sortType' => 'new'];
if ($cursor) $query['cursor'] = $cursor;
$data = call("$base/v1/reddit/posts?" . http_build_query($query), $key);
$new = 0;
foreach ($data['body'] as $p) {
if (!empty($p['stickied'])) continue; // pinned posts are old and always on top
$exists->execute([$p['id']]);
$isNew = $exists->fetchColumn() === false;
$upsert->execute([
':id' => $p['id'],
':subreddit' => $p['subreddit'],
':title' => html_entity_decode($p['title'], ENT_QUOTES | ENT_HTML5),
':author' => $p['author'],
':score' => (int) ($p['score'] ?? 0),
':num_comments' => (int) ($p['num_comments'] ?? 0),
':upvote_ratio' => $p['upvote_ratio'] ?? null,
':created_utc' => (int) $p['created_utc'],
':permalink' => 'https://www.reddit.com' . $p['permalink'],
':url' => html_entity_decode($p['url'] ?? '', ENT_QUOTES | ENT_HTML5),
':media_type' => mediaType($p),
':over_18' => !empty($p['over_18']) ? 1 : 0,
':now' => time(),
]);
$isNew ? $added++ : $updated++;
$new += $isNew ? 1 : 0;
}
echo "page $page: {$new} new\n";
$cursor = $data['meta']['cursor'] ?? null;
if ($new === 0 || !$cursor) break; // a page we already hold means we caught up
usleep(300000);
}
echo "r/$subreddit: $added added, $updated refreshed, " . $db->query('SELECT COUNT(*) FROM posts')->fetchColumn() . " rows in the archive\n";
The Node.js script
Save this as reddit_archive.mjs:
import { DatabaseSync } from "node:sqlite";
const BASE = "https://api.steadyapi.com";
const KEY = process.env.STEADYAPI_KEY;
const subreddit = process.argv[2] || "learnpython";
const MAX_PAGES = 4;
const db = new DatabaseSync("reddit_archive.db");
db.exec(`CREATE TABLE IF NOT EXISTS posts (
id TEXT PRIMARY KEY,
subreddit TEXT, title TEXT, author TEXT,
score INTEGER, num_comments INTEGER, upvote_ratio REAL,
created_utc INTEGER, permalink TEXT, url TEXT,
media_type TEXT, over_18 INTEGER,
first_seen INTEGER, last_seen INTEGER
)`);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Reddit text arrives with HTML entities such as &
const decode = (s = "") =>
s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'");
async function call(path, params) {
let failures = 0;
for (let attempt = 0; attempt < 4; attempt++) {
const res = await fetch(`${BASE}/v1/reddit/${path}?${new URLSearchParams(params)}`, {
headers: { Authorization: `Bearer ${KEY}` },
signal: AbortSignal.timeout(90000),
});
if ([429, 500, 502, 503].includes(res.status)) {
await sleep(2 ** attempt * 1000);
continue;
}
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
if (data.success === false) {
if (++failures < 2) {
await sleep(2000); // some requests fail once and then work, so retry one time
continue;
}
throw new Error(data.message);
}
return data;
}
throw new Error("request failed after retries");
}
function mediaType(p) {
const url = p.url || "";
if (p.is_video) return "video";
if (url.includes("/gallery/")) return "gallery";
if (/\.(jpe?g|png|gif|webp)(\?|$)/i.test(url) || p.domain === "i.redd.it") return "image";
return p.is_self ? "text" : "link";
}
const exists = db.prepare("SELECT 1 FROM posts WHERE id = ?");
const upsert = db.prepare(`INSERT INTO posts
(id, subreddit, title, author, score, num_comments, upvote_ratio, created_utc, permalink, url, media_type, over_18, first_seen, last_seen)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(id) DO UPDATE SET score = excluded.score, num_comments = excluded.num_comments,
upvote_ratio = excluded.upvote_ratio, last_seen = excluded.last_seen`);
let cursor = null;
let added = 0;
let updated = 0;
for (let page = 1; page <= MAX_PAGES; page++) {
const params = { subreddit, sortType: "new" };
if (cursor) params.cursor = cursor;
const data = await call("posts", params);
let fresh = 0;
for (const p of data.body) {
if (p.stickied) continue; // pinned posts are old and always on top
const isNew = !exists.get(p.id);
const now = Math.floor(Date.now() / 1000);
upsert.run(
p.id, p.subreddit, decode(p.title), p.author,
p.score ?? 0, p.num_comments ?? 0, p.upvote_ratio ?? null,
p.created_utc, "https://www.reddit.com" + p.permalink, decode(p.url),
mediaType(p), p.over_18 ? 1 : 0, now, now,
);
if (isNew) { added++; fresh++; } else { updated++; }
}
console.log(`page ${page}: ${fresh} new`);
cursor = data.meta.cursor;
if (fresh === 0 || !cursor) break; // a page we already hold means we caught up
await sleep(300);
}
const total = db.prepare("SELECT COUNT(*) AS n FROM posts").get().n;
console.log(`r/${subreddit}: ${added} added, ${updated} refreshed, ${total} rows in the archive`);
Run it twice
export STEADYAPI_KEY="your_api_key"
php reddit_archive.php pics # or: node reddit_archive.mjs pics
php reddit_archive.php pics
The first run on r/pics:
page 1: 24 new
page 2: 25 new
page 3: 25 new
page 4: 25 new
r/pics: 99 added, 0 refreshed, 99 rows in the archive
The second run, a few seconds later:
page 1: 0 new
r/pics: 0 added, 24 refreshed, 99 rows in the archive
The second run stopped after one page: 2 requests instead of 8. It also refreshed the scores of the 24 posts on that page.
Now ask the table a question:
sqlite3 reddit_archive.db "SELECT media_type, COUNT(*) FROM posts GROUP BY 1;"
gallery|19
image|80
Those 99 posts span about 58 hours. On r/pics, 80 were direct images and 19 were galleries.
Limits to plan for
- Run often enough. Four pages cover about 100 posts. A subreddit that gets more than that between runs leaves a gap. Raise
maxPages, or run more often. Check the gap by comparing the oldestcreated_utcin a run with the newest in the previous one. - Only the newest page is refreshed. A post's score stops updating once it falls off page 1 of a catch-up run. That is usually fine, because most scores settle within a day.
- Responses are cached for about 15 minutes, so running more often than that returns the same page.
- Some requests fail once. Both scripts retry once on
success: false, and back off on 429 and 5xx responses. - Check Reddit's terms for how you may store and use post content, especially if you plan to republish it.
Cost
A first run of 4 pages costs 8 requests: 4 listing calls at weight 2. A catch-up run costs 2. An hourly run that catches up in one page is 48 requests a day, or about 1,440 a month, so that schedule needs a paid plan. The Free plan's 500 requests a month covers about 60 full runs or 250 catch-up runs, and the Starter plan ($14.99/mo, 10,000 requests) covers about 1,250 full runs. The standard rate limit is 10 requests per second per account, and only HTTP 200 responses count toward your quota.
Bonus: ask the question 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 subreddit posted this week in plain English, before you build the archive.
Conclusion
You paged through a subreddit with a cursor, classified each post by media type, saved it to SQLite with an upsert, and made repeat runs stop as soon as they caught up. Schedule the script with cron, and change the SQL to ask your own questions.
Create a free account at steadyapi.com (no card required) and point the script at a community you follow. The API documentation lists every Reddit parameter with ready-made examples in cURL, JavaScript, PHP, and Python.