# Substack Newsletter Posts Extractor (`pecopeko/substack-newsletter-posts-extractor`) Actor

Extract public Substack newsletter posts, authors, publication dates, tags & clean RAG-ready Markdown/text from official /api/v1/archive and /feed RSS endpoints. Zero browser, zero paywall bypass — honestly flags subscriber-only previews.

- **URL**: https://apify.com/pecopeko/substack-newsletter-posts-extractor.md
- **Developed by:** [peco](https://apify.com/pecopeko) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $1.00 / 1,000 post extracteds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

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

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
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.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## 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.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Substack Newsletter Posts & Public Markdown Extractor

Extract structured newsletter posts, engagement counts (`reaction_count`, `comment_count`, `restacks`), podcast audio URLs, authors, and **LLM/RAG-ready Markdown & plain text** from any Substack publication (handles, `*.substack.com` URLs, or custom domains) — at **$1.00 per 1,000 posts** with zero headless browsers.

### Strictly Lawful & Transparent Paywall Handling

This Actor uses **publicly accessible archive JSON (`/api/v1/archive`), public RSS (`/feed`), and public free post endpoints only**:

- **Free public posts (`audience == "everyone"`)**: Enriched with full `body_markdown` and `body_text`, labeled `paywall_status: "free_public"`.
- **Paid / subscriber-only posts**: **Never** bypasses paywalls or logins. Honestly labeled `paywall_status: "paid_preview_only"` with only the public title, metadata, and archive preview text.

### Key Features

- **Handles, Subdomains & Custom Domains**: Pass `"pragmaticengineer"`, `"https://pragmaticengineer.substack.com"`, or `"https://newsletter.pragmaticengineer.com"` interchangeably.
- **Smart Pagination + RSS Merging**: Automatically paginates Substack's cursor-based `/api/v1/archive` endpoint (with legacy offset fallback), merges `/feed` RSS content in a single request to minimize network calls, and gracefully falls back to `/feed` RSS on non-Substack newsletter domains.
- **LLM & RAG Ready Output**: Clean `body_markdown` (preserving headings, links, lists, blockquotes, code blocks) plus plain `body_text`, `word_count`, `authors`, `post_date`, and `podcast_url`.
- **Precision Filtering**: Filter by `onlyFree`, `publishedAfter` (with early pagination cutoff), and `keywordFilter`.
- **Hardened Security & Reliability**: Full SSRF protection (blocks private, loopback, link-local, and cloud metadata IPs on initial URLs and every redirect hop), DTD/ENTITY XML hardening, polite rate limiting with `429`/`503` `Retry-After` backoff, and fault-isolated batch execution.

### Pricing (Pay-Per-Event)

- **`post_extracted`**: **`$0.001`** per extracted post (`$1.00 / 1,000 posts`). Error records are never charged.

### Popular Use Cases

1. **AI Research & RAG Pipelines**: Continuously index public tech, finance, and macro Substacks into clean Markdown chunks (`onlyFree: true`, `publishedAfter: "2026-01-01"`).
2. **Creator & Audience Analytics**: Track posting cadence, `reaction_count`, `comment_count`, `restacks`, and free vs. paid ratio across newsletter cohorts.
3. **Topic & Competitor Intelligence**: Monitor mentions of specific startups, frameworks, or tickers with `keywordFilter`.

### Input Example

```json
{
  "publications": [
    "pragmaticengineer",
    "https://www.astralcodexten.com"
  ],
  "maxPostsPerPublication": 25,
  "includeFullText": true,
  "onlyFree": false,
  "publishedAfter": "2026-01-01",
  "keywordFilter": "",
  "requestDelayMs": 350
}
```

### Output Example

```json
{
  "record_type": "post",
  "status": "ok",
  "publication": "newsletter.pragmaticengineer.com",
  "publication_url": "https://newsletter.pragmaticengineer.com",
  "post_id": 225268679,
  "title": "Software factories and code reviews with Harjot Gill",
  "subtitle": "CodeRabbit CEO Harjot Gill explains how he shipped over 5,000 pull requests in a month.",
  "slug": "software-factories-and-code-reviews",
  "canonical_url": "https://newsletter.pragmaticengineer.com/p/software-factories-and-code-reviews",
  "post_date": "2026-11-18T18:08:52.693Z",
  "audience": "everyone",
  "paywall_status": "free_public",
  "authors": ["Gergely Orosz"],
  "reaction_count": 70,
  "comment_count": 1,
  "restacks": 6,
  "word_count": 2388,
  "podcast_url": "https://api.substack.com/api/v1/audio/upload/example/src",
  "cover_image": "https://substackcdn.com/image/fetch/example.png",
  "body_markdown": "## Key Takeaways\n\nCode review throughput scales with automated static checks...",
  "body_text": "Key Takeaways\n\nCode review throughput scales with automated static checks...",
  "source_api": "substack_archive+rss"
}
```

# Actor input Schema

## `publications` (type: `array`):

List of Substack handles (e.g. 'pragmaticengineer'), Substack URLs (e.g. 'https://pragmaticengineer.substack.com'), or custom newsletter domains (e.g. 'https://newsletter.pragmaticengineer.com').

## `maxPostsPerPublication` (type: `integer`):

Maximum number of newest matching posts to extract per publication.

## `includeFullText` (type: `boolean`):

Merge public full-article HTML into clean body_markdown and body_text from /feed RSS or public /api/v1/posts/{slug} strictly for free (audience='everyone') posts. Paywalled posts return honest public preview text only.

## `onlyFree` (type: `boolean`):

When enabled, skip subscriber-only/paywalled posts and return only free public (audience='everyone') articles.

## `publishedAfter` (type: `string`):

Optional ISO-8601 date or timestamp (e.g. '2026-01-01') to stop pagination once posts are older than this cutoff.

## `keywordFilter` (type: `string`):

Optional case-insensitive keyword filter matched against publication name, post title, subtitle, and extracted text.

## `requestDelayMs` (type: `integer`):

Polite delay in milliseconds between archive pages and public post fetches. 429/503 responses automatically trigger Retry-After backoff.

## Actor input object example

```json
{
  "publications": [
    "pragmaticengineer"
  ],
  "maxPostsPerPublication": 25,
  "includeFullText": true,
  "onlyFree": false,
  "requestDelayMs": 350
}
```

# Actor output Schema

## `results` (type: `string`):

Structured JSON records extracted during this Actor run.

# 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 = {
    "publications": [
        "pragmaticengineer"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("pecopeko/substack-newsletter-posts-extractor").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 = { "publications": ["pragmaticengineer"] }

# Run the Actor and wait for it to finish
run = client.actor("pecopeko/substack-newsletter-posts-extractor").call(run_input=run_input)

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

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

```

## CLI example

```bash
echo '{
  "publications": [
    "pragmaticengineer"
  ]
}' |
apify call pecopeko/substack-newsletter-posts-extractor --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,pecopeko/substack-newsletter-posts-extractor"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/M1H4sYWZsCcACbA2J/builds/iZ9UtJVBIhG2EJreQ/openapi.json
