# Reddit Scraper (`gentle_cloud/reddit-scraper`) Actor

Scrape posts and comments from any Reddit subreddit. Supports multiple subreddits, search, sorting, time filters, and optional comment extraction — no API key required.

- **URL**: https://apify.com/gentle\_cloud/reddit-scraper.md
- **Developed by:** [Monkey Coder](https://apify.com/gentle_cloud) (community)
- **Categories:** Social media, SEO tools, News
- **Stats:** 31 total users, 10 monthly users, 100.0% runs succeeded, 1 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/platform/actors/running/actors-in-store#pay-per-usage

## What's an Apify Actor?

Actors are web data automations that power AI and operations. They run on the Apify platform to scrape websites, process data, connect APIs, and automate workflows.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.
Actors are written with capital "A".

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.
The best way to integrate Actors is as follows.

- **AI agents and MCP clients** — the [Apify MCP server](https://docs.apify.com/integrations/mcp.md) at `https://mcp.apify.com` (remote, streamable HTTP, OAuth on first use).
- **Agentic workflows and local Actor development** — [Agent Skills](https://apify.com/.well-known/agent-skills/index.json) with the [Apify CLI](https://docs.apify.com/cli/docs.md): `npm install -g apify-cli`, then `apify login`.
- **JavaScript/TypeScript projects** — the official [JS/TS client](https://docs.apify.com/api/client/js/docs.md): `npm install apify-client`.
- **Python projects** — the official [Python client](https://docs.apify.com/api/client/python/docs.md): `pip install apify-client`.
- **Any other language** — the [REST API](https://docs.apify.com/api/v2.md).

For usage examples, see the [API](#api) section below.

For more details, see Apify documentation as [Markdown index](https://docs.apify.com/llms.txt) and [Markdown full-text](https://docs.apify.com/llms-full.txt).

# README

## 📡 Reddit Scraper

Scrape posts and comments from any Reddit subreddit — no API key, no login required.

### Why use this Actor

Use this Actor when you need Reddit data fast without managing browsers or API keys. It’s a good fit for content research, community monitoring, trend spotting, and lead discovery.

### ✨ Features

- **Multiple subreddits** — Scrape several subreddits in a single run
- **Flexible sorting** — Hot, New, Top, Rising, or Controversial
- **Time filters** — Past hour, day, week, month, year, or all time
- **Search within subreddits** — Filter posts by keyword
- **Comment extraction** — Optionally fetch and flatten comment trees
- **Rich post data** — Title, author, score, upvote ratio, flair, preview images, awards, and more
- **No API key needed** — Uses Reddit's public `.json` endpoints

### 🔧 How It Works

1. The Actor sends HTTP requests to Reddit's public JSON endpoints (e.g., `reddit.com/r/python/hot.json`)
2. Posts are extracted from the paginated response (up to 100 per page)
3. If comments are enabled, each post's comment thread is fetched and the nested tree is flattened
4. Built-in rate limiting (2–4 second delays) prevents Reddit from blocking requests
5. Results are pushed to the Apify dataset as flat JSON objects

### 📥 Input Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `subreddits` | String | `python` | Comma-separated subreddit names (without `r/` prefix) |
| `sort` | Select | `hot` | Sort mode: hot, new, top, rising, controversial |
| `time_filter` | Select | `week` | Time range for top/controversial: hour, day, week, month, year, all |
| `max_posts` | Integer | `25` | Max posts per subreddit (1–1000) |
| `search_query` | String | *(empty)* | Optional keyword search within each subreddit |
| `include_comments` | Boolean | `false` | Fetch comments for each post (slower due to rate limiting) |
| `max_comments_per_post` | Integer | `10` | Max comments per post when comments are enabled |
| `comment_sort` | Select | `top` | Comment sort: best, top, new, controversial, old, qa |

### 📤 Sample Output

#### Post (without comments)

```json
{
    "post_id": "1abc2de",
    "title": "Python 3.13 released with major performance improvements",
    "author": "guido_van_rossum",
    "subreddit": "python",
    "score": 4523,
    "upvote_ratio": 0.97,
    "num_comments": 312,
    "url": "https://docs.python.org/3.13/whatsnew/3.13.html",
    "permalink": "https://www.reddit.com/r/python/comments/1abc2de/python_313_released/",
    "is_self": false,
    "selftext": "",
    "domain": "docs.python.org",
    "flair": "News",
    "is_video": false,
    "over_18": false,
    "spoiler": false,
    "stickied": false,
    "created_utc": "2025-10-01T14:30:00+00:00",
    "thumbnail": "https://b.thumbs.redditmedia.com/...",
    "preview_image": "https://preview.redd.it/...",
    "total_awards": 5,
    "gilded": 2,
    "num_crossposts": 3,
    "fetched_at": "2025-12-15T10:00:00+00:00"
}
```

#### Comment (when `include_comments` is enabled)

Comments are included as an array in each post's `comments` field:

```json
{
    "comment_id": "k7xyz99",
    "post_id": "1abc2de",
    "author": "pythonista42",
    "body": "The new JIT compiler is incredible. 2x speedup on my workloads.",
    "score": 891,
    "depth": 0,
    "is_submitter": false,
    "parent_id": "t3_1abc2de",
    "permalink": "https://www.reddit.com/r/python/comments/1abc2de/.../k7xyz99/",
    "stickied": false,
    "distinguished": "",
    "controversiality": 0,
    "created_utc": "2025-10-01T15:00:00+00:00",
    "fetched_at": "2025-12-15T10:00:30+00:00"
}
```

### 🚀 Quick Start

1. Add one or more subreddit names in `subreddits` (example: `python,javascript`).
2. Turn on `include_comments` only when you need comment threads.
3. Run the Actor and check that each item includes `post_id`, `title`, `subreddit`, and `fetched_at`.

### 🔍 Verification Steps

- Run a small test input first: `subreddits = python`, `max_posts = 5`.
- Confirm the dataset contains flat post objects and the `fetched_at` timestamp.
- If comments are enabled, verify `comments_fetched` is present and greater than 0 on at least one post.

### 🧪 Example Inputs

**Basic post scrape**

```json
{
  "subreddits": "python,javascript",
  "sort": "hot",
  "max_posts": 5
}
```

**Search + comments**

```json
{
  "subreddits": "learnprogramming",
  "search_query": "api",
  "include_comments": true,
  "max_posts": 10,
  "max_comments_per_post": 5,
  "comment_sort": "top"
}
```

### ⚠️ Notes

- **Authentication**: Uses Reddit OAuth API with application-only auth. Requires a Reddit OAuth client ID (set via `REDDIT_CLIENT_ID` environment variable).
- **Rate limiting**: Reddit allows 100 OAuth requests per minute per client. The Actor uses 1–2 second delays between requests.
- **Post text truncation**: `selftext` is truncated to 2,000 characters; comment `body` to 3,000 characters. Enable OAuth for longer content.
- **Pagination limit**: Reddit caps listing access at ~1,000 posts per subreddit for unauthenticated requests.

### 💡 Troubleshooting

- If you see no results, verify the subreddit exists and the spelling is valid.
- If OAuth fails, set `REDDIT_CLIENT_ID` in the Actor environment variables.
- For comment scraping, use smaller `max_posts` values to keep runs fast and reliable.
- For private or restricted communities, the Actor may return partial or no data.

# Actor input Schema

## `subreddits` (type: `string`):

Comma-separated list of subreddit names to scrape (without r/ prefix). Example: python,javascript,datascience

## `sort` (type: `string`):

How to sort posts within each subreddit.

## `time_filter` (type: `string`):

Time range filter (applies to 'top' and 'controversial' sort modes).

## `max_posts` (type: `integer`):

Maximum number of posts to fetch from each subreddit (max 1000).

## `search_query` (type: `string`):

Optional search query to filter posts within each subreddit. Leave empty to browse without searching.

## `include_comments` (type: `boolean`):

Whether to fetch comments for each post. Enabling this significantly increases run time due to rate limiting.

## `max_comments_per_post` (type: `integer`):

Maximum number of comments to fetch per post (only used when Include Comments is enabled).

## `comment_sort` (type: `string`):

How to sort comments (only used when Include Comments is enabled).

## Actor input object example

```json
{
  "subreddits": "python",
  "sort": "hot",
  "time_filter": "week",
  "max_posts": 25,
  "max_comments_per_post": 10,
  "comment_sort": "top"
}
```

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "subreddits": "python",
    "sort": "hot",
    "time_filter": "week",
    "max_posts": 25,
    "search_query": "",
    "include_comments": false,
    "max_comments_per_post": 10,
    "comment_sort": "top"
};

// Run the Actor and wait for it to finish
const run = await client.actor("gentle_cloud/reddit-scraper").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "subreddits": "python",
    "sort": "hot",
    "time_filter": "week",
    "max_posts": 25,
    "search_query": "",
    "include_comments": False,
    "max_comments_per_post": 10,
    "comment_sort": "top",
}

# Run the Actor and wait for it to finish
run = client.actor("gentle_cloud/reddit-scraper").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print("💾 Check your data here: https://console.apify.com/storage/datasets/" + run["defaultDatasetId"])
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "subreddits": "python",
  "sort": "hot",
  "time_filter": "week",
  "max_posts": 25,
  "search_query": "",
  "include_comments": false,
  "max_comments_per_post": 10,
  "comment_sort": "top"
}' |
apify call gentle_cloud/reddit-scraper --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "command": "npx",
            "args": [
                "mcp-remote",
                "https://mcp.apify.com/?tools=gentle_cloud/reddit-scraper",
                "--header",
                "Authorization: Bearer <YOUR_API_TOKEN>"
            ]
        }
    }
}

```

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/acts/S8NthQwPkVw4N8g15/builds/OcdsQEimFNHo4ZSo2/openapi.json
