3 min read

Reddit API Interaction with PRAW

This guide demonstrates how to interact with the Reddit API using PRAW (Python Reddit API Wrapper). PRAW simplifies the process of accessing Reddit's API, handling authentication and rate limiting automatically.

Modules Used:

  • praw: The Python Reddit API Wrapper.
  • python-dotenv: To securely manage API credentials.
  • argparse: To handle command-line arguments.

Prerequisites

  1. Reddit Account: You need a Reddit account.
  2. Create an App:
    • Go to https://www.reddit.com/prefs/apps.
    • Click create another app... (or "are you a developer? create an app...").
    • Select script.
    • Fill in name and description.
    • For redirect uri, you can use http://localhost:8080 (not used for script apps but required).
    • Click create app.
  3. Credentials: Note down the client ID (under the name) and client secret.

Installation

pip install praw python-dotenv

Setup

Create a .env file in your project directory:

REDDIT_CLIENT_ID=your_client_id
REDDIT_CLIENT_SECRET=your_client_secret
REDDIT_USER_AGENT=python:my_reddit_tool:v1.0 (by /u/yourusername)

The Code

Save this as reddit_tool.py.

import praw
import os
import argparse
import sys
from dotenv import load_dotenv

# Load Config
load_dotenv()

def get_reddit():
    try:
        return praw.Reddit(
            client_id=os.getenv("REDDIT_CLIENT_ID"),
            client_secret=os.getenv("REDDIT_CLIENT_SECRET"),
            user_agent=os.getenv("REDDIT_USER_AGENT", "python:script:v1.0")
        )
    except Exception as e:
        print(f"Configuration Error: {e}")
        sys.exit(1)

def get_hot_posts(subreddit_name, limit=5):
    reddit = get_reddit()
    print(f"Fetching hot posts from r/{subreddit_name}...")

    try:
        subreddit = reddit.subreddit(subreddit_name)

        # Iterating triggers the API request
        for submission in subreddit.hot(limit=limit):
            print(f"\nTitle: {submission.title}")
            print(f"Score: {submission.score} | Comments: {submission.num_comments}")
            print(f"URL:   {submission.url}")

    except Exception as e:
        print(f"Error: {e}")

def get_user_info(username):
    reddit = get_reddit()
    print(f"Fetching info for u/{username}...")

    try:
        user = reddit.redditor(username)
        # Accessing attributes triggers the fetch
        print(f"\n--- User: {user.name} ---")
        print(f"ID: {user.id}")
        print(f"Link Karma: {user.link_karma}")
        print(f"Comment Karma: {user.comment_karma}")

    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Reddit API Tool with PRAW")
    subparsers = parser.add_subparsers(dest="command", help="Command to run")

    # Subreddit Command
    sub_parser = subparsers.add_parser("subreddit", help="Get hot posts from a subreddit")
    sub_parser.add_argument("name", help="Subreddit name")
    sub_parser.add_argument("--limit", type=int, default=5, help="Number of posts")

    # User Command
    user_parser = subparsers.add_parser("user", help="Get user information")
    user_parser.add_argument("name", help="Reddit username")

    args = parser.parse_args()

    if args.command == "subreddit":
        get_hot_posts(args.name, args.limit)
    elif args.command == "user":
        get_user_info(args.name)
    else:
        parser.print_help()

Usage

# Get hot posts from r/python
python reddit_tool.py subreddit python --limit 3

# Get user stats
python reddit_tool.py user spez

programming/python/python