Agent skill

Reddit API

by alinaqi in alinaqi/maggy

Reddit API with PRAW (Python) and Snoowrap (Node.js). An agent skill from alinaqi/maggy.

MITAuto-check: notesBackend & APIs

Install Reddit API

skills CLI
$ npx skills add alinaqi/maggy --skill reddit-api -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install alinaqi/maggy reddit-api --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/alinaqi/maggy.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/reddit-api .claude/skills/reddit-api && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
reddit-api
GitHub stars
707
Token cost
~3.6k tokens
SKILL.md length
318 words
Files
1
Skills in repo
71
Repo updated
First seen
Licence
MIT

At a glance

Reddit API with PRAW (Python) and Snoowrap (Node.js). An agent skill from alinaqi/maggy.

  • Works in 2 steps: Create Reddit App → Environment Variables
  • Backend & APIs work in your project
  • SKILL.md covers Setup, Rate Limits, Python: PRAW (Recommended) and TypeScript / Node.js: Snoowrap, plus 7 more sections
  • Calls pip, npm and uv; reaches reddit.com and oauth.reddit.com; needs REDDIT_CLIENT_SECRET and REDDIT_PASSWORD

What it does

Reddit API is an agent skill from alinaqi/maggy. Reddit API with PRAW (Python) and Snoowrap (Node.js)

Its SKILL.md is about 3.6k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Backend & APIs. It works with Reddit, Python and Node.js. The repository describes itself as: What started as an opinionated Claude Code setup kit is now an autonomous AI engineering command center. The licence is MIT.

When your agent uses it

  • Backend & APIs work in your project

Example prompts

  • “/reddit-api”

Requirements

  • Python 3
  • Node.js
  • A credential in REDDIT_CLIENT_SECRET

Workflow steps

2 steps, taken from the step headings in SKILL.md.

  1. Create Reddit App
  2. Environment Variables

What it can do on your machine

Read from SKILL.md and the folder at commit 72a456e. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • pip
    • npm
    • uv
    • pnpm
    • python

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Hosts in commands or code, which the agent is likely to contact:

    • reddit.com
    • oauth.reddit.com

    Also links to:

    • github.com
    • praw.readthedocs.io

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • REDDIT_CLIENT_SECRET
    • REDDIT_PASSWORD

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Reddit API loads about 3.6k tokens when it runs. Until then it costs about 16 tokens; SKILL.md has 318 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~16
When it runs · the whole SKILL.md, loaded when a task matches
~3.6k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check: notes

The automated check noted patterns worth knowing about, such as sudo or a known installer.

  • NoteMentions a .env fileSKILL.md:36
    # .env
  • NoteMentions a .env fileSKILL.md:85
    env_file = ".env"
  • NoteMentions a .env fileSKILL.md:504
    ├── .env

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from alinaqi/maggy at commit 72a456e, republished under its MIT licence (© alinaqi). 318 words, ~3,564 tokens.

Download SKILL.mdSave it as .claude/skills/reddit-api/SKILL.md (or your agent's skills folder).
name
reddit-api
description
Reddit API with PRAW (Python) and Snoowrap (Node.js)
when-to-use
When building Reddit integrations or bots
user-invocable
false
effort
medium

Reddit API Skill

For integrating Reddit data into applications - fetching posts, comments, subreddits, and user data.

Sources: Reddit API Docs | OAuth2 Wiki | PRAW Docs


Setup

1. Create Reddit App
  1. Go to https://www.reddit.com/prefs/apps
  2. Click "Create App" or "Create Another App"
  3. Fill in:
    • Name: Your app name
    • App type:
      • script - For personal use / bots you control
      • web app - For server-side apps with user auth
      • installed app - For mobile/desktop apps
    • Redirect URI: http://localhost:8000/callback (for dev)
  4. Note your client_id (under app name) and client_secret
2. Environment Variables
bash
# .env
REDDIT_CLIENT_ID=your_client_id
REDDIT_CLIENT_SECRET=your_client_secret
REDDIT_USER_AGENT=YourApp/1.0 by YourUsername
REDDIT_USERNAME=your_username        # For script apps only
REDDIT_PASSWORD=your_password        # For script apps only

User-Agent Format: <platform>:<app_id>:<version> (by /u/<username>)


Rate Limits

TierLimitNotes
OAuth authenticated100 QPMPer OAuth client ID
Non-authenticatedBlockedMust use OAuth
  • Limits averaged over 10-minute window
  • Include User-Agent header to avoid blocks
  • Respect X-Ratelimit-* response headers

Installation
bash
pip install praw
# or
uv add praw
Script App (Personal Use / Bots)
python
import praw
from pydantic_settings import BaseSettings

class RedditSettings(BaseSettings):
    reddit_client_id: str
    reddit_client_secret: str
    reddit_user_agent: str
    reddit_username: str
    reddit_password: str

    class Config:
        env_file = ".env"

settings = RedditSettings()

reddit = praw.Reddit(
    client_id=settings.reddit_client_id,
    client_secret=settings.reddit_client_secret,
    user_agent=settings.reddit_user_agent,
    username=settings.reddit_username,
    password=settings.reddit_password,
)

# Verify authentication
print(f"Logged in as: {reddit.user.me()}")
Read-Only (No User Auth)
python
import praw

reddit = praw.Reddit(
    client_id="your_client_id",
    client_secret="your_client_secret",
    user_agent="YourApp/1.0 by YourUsername",
)

# Read-only mode - can browse, can't post/vote
reddit.read_only = True
Common Operations
python
# Get subreddit posts
subreddit = reddit.subreddit("python")

# Hot posts
for post in subreddit.hot(limit=10):
    print(f"{post.title} - {post.score} upvotes")

# New posts
for post in subreddit.new(limit=10):
    print(post.title)

# Search posts
for post in subreddit.search("pydantic", limit=5):
    print(post.title)

# Get specific post
submission = reddit.submission(id="abc123")
print(submission.title)
print(submission.selftext)

# Get comments
submission.comments.replace_more(limit=0)  # Flatten comment tree
for comment in submission.comments.list():
    print(f"{comment.author}: {comment.body[:100]}")
Posting & Voting (Requires Auth)
python
# Submit text post
subreddit = reddit.subreddit("test")
submission = subreddit.submit(
    title="Test Post",
    selftext="This is the body of my post."
)

# Submit link post
submission = subreddit.submit(
    title="Check this out",
    url="https://example.com"
)

# Vote
submission.upvote()
submission.downvote()
submission.clear_vote()

# Comment
submission.reply("Great post!")

# Reply to comment
comment = reddit.comment(id="xyz789")
comment.reply("I agree!")
Streaming (Real-time)
python
# Stream new posts
for post in reddit.subreddit("python").stream.submissions():
    print(f"New post: {post.title}")
    # Process post...

# Stream new comments
for comment in reddit.subreddit("python").stream.comments():
    print(f"New comment by {comment.author}: {comment.body[:50]}")
User Data
python
# Get user info
user = reddit.redditor("spez")
print(f"Karma: {user.link_karma + user.comment_karma}")

# User's posts
for post in user.submissions.new(limit=5):
    print(post.title)

# User's comments
for comment in user.comments.new(limit=5):
    print(comment.body[:100])

TypeScript / Node.js: Snoowrap

Installation
bash
npm install snoowrap
# or
pnpm add snoowrap
Setup
typescript
import Snoowrap from "snoowrap";

const reddit = new Snoowrap({
  userAgent: "YourApp/1.0 by YourUsername",
  clientId: process.env.REDDIT_CLIENT_ID!,
  clientSecret: process.env.REDDIT_CLIENT_SECRET!,
  username: process.env.REDDIT_USERNAME!,
  password: process.env.REDDIT_PASSWORD!,
});

// Configure rate limiting
reddit.config({
  requestDelay: 1000,  // 1 second between requests
  continueAfterRatelimitError: true,
});
Common Operations
typescript
// Get hot posts from subreddit
const posts = await reddit.getSubreddit("typescript").getHot({ limit: 10 });
posts.forEach((post) => {
  console.log(`${post.title} - ${post.score} upvotes`);
});

// Search posts
const results = await reddit.getSubreddit("programming").search({
  query: "typescript",
  sort: "relevance",
  time: "month",
  limit: 10,
});

// Get specific post
const submission = await reddit.getSubmission("abc123").fetch();
console.log(submission.title);

// Get comments
const comments = await submission.comments.fetchAll();
comments.forEach((comment) => {
  console.log(`${comment.author.name}: ${comment.body.slice(0, 100)}`);
});
Posting
typescript
// Submit text post
const post = await reddit.getSubreddit("test").submitSelfpost({
  title: "Test Post",
  text: "This is the body.",
});

// Submit link
const linkPost = await reddit.getSubreddit("test").submitLink({
  title: "Check this out",
  url: "https://example.com",
});

// Vote and comment
await post.upvote();
await post.reply("Great post!");

Direct API (No Library)

Python with httpx
python
import httpx
import base64
from pydantic import BaseModel

class RedditClient:
    def __init__(self, client_id: str, client_secret: str, user_agent: str):
        self.client_id = client_id
        self.client_secret = client_secret
        self.user_agent = user_agent
        self.access_token: str | None = None
        self.client = httpx.AsyncClient()

    async def authenticate(self) -> None:
        """Get application-only OAuth token."""
        auth = base64.b64encode(
            f"{self.client_id}:{self.client_secret}".encode()
        ).decode()

        response = await self.client.post(
            "https://www.reddit.com/api/v1/access_token",
            headers={
                "Authorization": f"Basic {auth}",
                "User-Agent": self.user_agent,
            },
            data={
                "grant_type": "client_credentials",
            },
        )
        response.raise_for_status()
        self.access_token = response.json()["access_token"]

    async def get_posts(self, subreddit: str, sort: str = "hot", limit: int = 10) -> list[dict]:
        """Get posts from a subreddit."""
        if not self.access_token:
            await self.authenticate()

        response = await self.client.get(
            f"https://oauth.reddit.com/r/{subreddit}/{sort}",
            headers={
                "Authorization": f"Bearer {self.access_token}",
                "User-Agent": self.user_agent,
            },
            params={"limit": limit},
        )
        response.raise_for_status()
        return [post["data"] for post in response.json()["data"]["children"]]

    async def close(self) -> None:
        await self.client.aclose()


# Usage
async def main():
    client = RedditClient(
        client_id="your_id",
        client_secret="your_secret",
        user_agent="YourApp/1.0",
    )
    try:
        posts = await client.get_posts("python", limit=5)
        for post in posts:
            print(f"{post['title']} - {post['score']} upvotes")
    finally:
        await client.close()
TypeScript with fetch
typescript
interface RedditPost {
  title: string;
  score: number;
  url: string;
  selftext: string;
  author: string;
  created_utc: number;
}

class RedditClient {
  private accessToken: string | null = null;

  constructor(
    private clientId: string,
    private clientSecret: string,
    private userAgent: string
  ) {}

  async authenticate(): Promise<void> {
    const auth = Buffer.from(`${this.clientId}:${this.clientSecret}`).toString("base64");

    const response = await fetch("https://www.reddit.com/api/v1/access_token", {
      method: "POST",
      headers: {
        Authorization: `Basic ${auth}`,
        "User-Agent": this.userAgent,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: "grant_type=client_credentials",
    });

    const data = await response.json();
    this.accessToken = data.access_token;
  }

  async getPosts(subreddit: string, sort = "hot", limit = 10): Promise<RedditPost[]> {
    if (!this.accessToken) await this.authenticate();

    const response = await fetch(
      `https://oauth.reddit.com/r/${subreddit}/${sort}?limit=${limit}`,
      {
        headers: {
          Authorization: `Bearer ${this.accessToken}`,
          "User-Agent": this.userAgent,
        },
      }
    );

    const data = await response.json();
    return data.data.children.map((child: any) => child.data);
  }
}

OAuth2 Web Flow (User Authorization)

For apps where users log in with their Reddit account:

python
from fastapi import FastAPI, Request
from fastapi.responses import RedirectResponse
import httpx
import secrets

app = FastAPI()
state_store: dict[str, bool] = {}

REDDIT_CLIENT_ID = "your_client_id"
REDDIT_CLIENT_SECRET = "your_client_secret"
REDIRECT_URI = "http://localhost:8000/callback"

@app.get("/login")
async def login():
    state = secrets.token_urlsafe(16)
    state_store[state] = True

    auth_url = (
        f"https://www.reddit.com/api/v1/authorize"
        f"?client_id={REDDIT_CLIENT_ID}"
        f"&response_type=code"
        f"&state={state}"
        f"&redirect_uri={REDIRECT_URI}"
        f"&duration=permanent"
        f"&scope=identity read submit vote"
    )
    return RedirectResponse(auth_url)

@app.get("/callback")
async def callback(code: str, state: str):
    if state not in state_store:
        return {"error": "Invalid state"}
    del state_store[state]

    # Exchange code for token
    async with httpx.AsyncClient() as client:
        response = await client.post(
            "https://www.reddit.com/api/v1/access_token",
            auth=(REDDIT_CLIENT_ID, REDDIT_CLIENT_SECRET),
            data={
                "grant_type": "authorization_code",
                "code": code,
                "redirect_uri": REDIRECT_URI,
            },
            headers={"User-Agent": "YourApp/1.0"},
        )

    tokens = response.json()
    # Store tokens securely, associate with user session
    return {"access_token": tokens["access_token"][:10] + "..."}

Available Scopes

ScopeDescription
identityAccess username and signup date
readAccess posts and comments
submitSubmit links and comments
voteUpvote/downvote content
editEdit posts and comments
historyAccess voting history
subscribeManage subreddit subscriptions
mysubredditsAccess subscribed subreddits
privatemessagesAccess private messages
saveSave/unsave content

Full list: https://www.reddit.com/api/v1/scopes


Project Structure

project/
├── src/
│   ├── reddit/
│   │   ├── __init__.py
│   │   ├── client.py         # Reddit client wrapper
│   │   ├── models.py         # Pydantic models for posts/comments
│   │   └── scraper.py        # Data collection logic
│   └── main.py
├── .env
└── pyproject.toml

Pydantic Models

python
from pydantic import BaseModel
from datetime import datetime

class RedditPost(BaseModel):
    id: str
    title: str
    author: str
    subreddit: str
    score: int
    upvote_ratio: float
    url: str
    selftext: str
    created_utc: datetime
    num_comments: int
    is_self: bool

    @classmethod
    def from_praw(cls, submission) -> "RedditPost":
        return cls(
            id=submission.id,
            title=submission.title,
            author=str(submission.author),
            subreddit=submission.subreddit.display_name,
            score=submission.score,
            upvote_ratio=submission.upvote_ratio,
            url=submission.url,
            selftext=submission.selftext,
            created_utc=datetime.fromtimestamp(submission.created_utc),
            num_comments=submission.num_comments,
            is_self=submission.is_self,
        )

class RedditComment(BaseModel):
    id: str
    author: str
    body: str
    score: int
    created_utc: datetime
    parent_id: str
    is_submitter: bool

Anti-Patterns

  • No User-Agent - Reddit blocks requests without proper User-Agent
  • Ignoring rate limits - Respect 100 QPM, check X-Ratelimit-* headers
  • Storing credentials in code - Use environment variables
  • Not handling MoreComments - Use replace_more() in PRAW
  • Polling instead of streaming - Use .stream for real-time data
  • No error handling - Handle 429 (rate limit), 403 (forbidden), 404 (not found)

Quick Reference

bash
# PRAW installation
pip install praw

# Snoowrap installation
npm install snoowrap

# Test authentication
python -c "import praw; r = praw.Reddit(...); print(r.user.me())"
Endpoints
OperationEndpoint
Auth tokenPOST https://www.reddit.com/api/v1/access_token
API requestshttps://oauth.reddit.com/...
Subreddit postsGET /r/{subreddit}/{sort}
SubmissionGET /comments/{id}
User infoGET /user/{username}/about
Submit postPOST /api/submit
VotePOST /api/vote

© alinaqi, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in skills/reddit-api of alinaqi/maggy.

Open the folder on GitHubat commit 72a456e

Compare with similar skills

Reddit API next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Reddit API compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Reddit API this skillalinaqi/maggy707—~3.6kAutomated safety check: NotesMIT
Cloudflare Email Servicehodgef/apiker1273 repos~2kAutomated safety check: PassMIT
Port Client Componentasyncapi/generator1.1k—~4.6kAutomated safety check: PassApache-2.0
Nxvutensils/nxv136—~7.9kAutomated safety check: NotesMIT
Adobe App Builder Action Scaffolderadobe/skills196—~3.1kAutomated safety check: PassApache-2.0
Sasjs Serversasjs/core132—~2.4kAutomated safety check: NotesMIT

Similar skills

  • Send and receive transactional emails with Cloudflare Email Service (Email Sending + Email Routing).

    127 GitHub starsUsed in 3 repos~2k tokens
    Backend & APIsAuto-check passed
  • Port Client Component

    asyncapi/generator

    Port a component or feature that already exists in one protocol client template to sibling clients under packages/templates/clients/<protocol/ that are missing it.

    1.1k GitHub stars~4.6k tokensUpdated 3 days ago
    Backend & APIsAuto-check passed
  • Nxv

    utensils/nxv

    Find any version of any Nix package across nixpkgs git history using the nxv CLI or HTTP API.

    136 GitHub stars~7.9k tokensUpdated 1 mo ago
    Backend & APIsAuto-check: notes
  • Scaffolds, implements, deploys and debugs Adobe Runtime actions in App Builder projects, with templates for webhooks, events, database CRUD, sequences and Asset Compute workers.

    196 GitHub stars~3.1k tokensUpdated yesterday
    Backend & APIsAuto-check passed
  • Sasjs Server

    sasjs/core

    Installing, configuring, and running @sasjs/server - the open-source NodeJS wrapper around the SAS binary that provides a REST API, filesystem (SASjs Drive), Stored Program execution, and web app…

    132 GitHub stars~2.4k tokensUpdated 3 days ago
    Backend & APIsAuto-check: notes
  • Fullstack Dev

    HHU3637kr/skills

    Full-stack backend architecture and frontend-backend integration guide.

    145 GitHub starsUsed in 3 repos~8.6k tokens
    Backend & APIsAuto-check: notes

More from alinaqi/maggy

All 71 skills in this repo
  • AI Models

    alinaqi/maggy

    Latest AI models reference - Claude, OpenAI, Gemini, Eleven Labs, Replicate

    707 GitHub starsUsed in 1 repo~4.1k tokens
    Auto-check passed
  • Azure Cosmosdb

    alinaqi/maggy

    Azure Cosmos DB partition keys, consistency levels, change feed, SDK patterns

    707 GitHub starsUsed in 1 repo~4.5k tokens
    Auto-check passed
  • LLM Patterns

    alinaqi/maggy

    AI-first application patterns, LLM testing, prompt management

    707 GitHub starsUsed in 1 repo~2.1k tokens
    Auto-check passed
  • Woocommerce

    alinaqi/maggy

    WooCommerce REST API - products, orders, customers, webhooks

    707 GitHub starsUsed in 1 repo~4.4k tokens
    Auto-check: notes
  • Aeo Optimization

    alinaqi/maggy

    AI Engine Optimization - semantic triples, page templates, content clusters for AI citations

    707 GitHub stars~3.7k tokensUpdated 14 days ago
    Auto-check passed
  • Agent Teams

    alinaqi/maggy

    Claude Code Agent Teams - default team-based development with strict TDD pipeline enforcement

    707 GitHub stars~5k tokensUpdated 14 days ago
    Auto-check: notes

Categories

Questions about Reddit API

What does Reddit API do?

Reddit API with PRAW (Python) and Snoowrap (Node.js). An agent skill from alinaqi/maggy. Reddit API is an agent skill from alinaqi/maggy.

When should I use Reddit API?

Reddit API fits situations like: backend & APIs work in your project.

How do I install Reddit API in Claude Code?

Run `npx skills add alinaqi/maggy --skill reddit-api -a claude-code`. Or copy the skill folder (skills/reddit-api in alinaqi/maggy) into .claude/skills/reddit-api in your project. Claude Code loads it when a task matches its description.

How do I install Reddit API in Codex?

Run `npx skills add alinaqi/maggy --skill reddit-api -a codex`. Or copy the skill folder (skills/reddit-api in alinaqi/maggy) into .agents/skills/reddit-api in your project. Codex loads it when a task matches its description.

Can I use Reddit API in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add alinaqi/maggy --skill reddit-api -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/reddit-api, .gemini/skills/reddit-api, .github/skills/reddit-api and .opencode/skills/reddit-api in your project.

What does Reddit API need to run?

Going by SKILL.md and its folder, Reddit API needs the command-line tools its instructions call (pip, npm, uv, pnpm and python) and credentials named REDDIT_CLIENT_SECRET and REDDIT_PASSWORD. Our summary lists: Python 3; Node.js; A credential in REDDIT_CLIENT_SECRET.

Does Reddit API access the network?

SKILL.md names 4 domains. In commands or code: reddit.com and oauth.reddit.com; the agent is likely to contact these when it follows the instructions. As links in the text: github.com and praw.readthedocs.io. This is read from the text; nothing was executed.

Is Reddit API safe to install?

Our automated static check of SKILL.md found notes only (mentions a .env file), nothing it rates as a warning. It is not a guarantee. Review the folder before installing.

What licence does Reddit API use?

Reddit API is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Reddit API use?

About 3.6k tokens (SKILL.md is roughly 14k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Reddit API?

Skills that share tags, products or a category with Reddit API: Cloudflare Email Service (hodgef/apiker, 127 stars), Port Client Component (asyncapi/generator, 1.1k stars), Nxv (utensils/nxv, 136 stars) and Adobe App Builder Action Scaffolder (adobe/skills, 196 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Reddit API?

alinaqi (a GitHub user) maintains it in alinaqi/maggy, which has 707 GitHub stars. The repository holds 71 skills in this directory. The repository was last updated on September 24, 2026.

Source: alinaqi/maggy on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.