JRAW Documentation

repository·master·Indexed 18 days ago

https://github.com/mattbdean/jraw

A Java Reddit API Wrapper for the JVM that provides a structured way to interact with Reddit's API. It supports OAuth2 authentication, various network adapters, and includes a dedicated extension library for Android integration.

Tokens
22.5K
Snippets
92
Records
122
Agent score
62%

What's inside JRAW

  1. Overview of JRAW package structure

    master

    JRAW is organized into several functional packages that handle different aspects of interacting with the Reddit API:

    • net.dean.jraw: The core central classes of the library.
    • net.dean.jraw.databind: Handles JSON to POJO (Plain Old Java Object) conversions using the Moshi library.
    • net.dean.jraw.http: Manages HTTP request/response lifecycle and logging, built on top of OkHttp.
    • net.dean.jraw.models: Contains data classes representing the structure of Reddit API responses.
    • net.dean.jraw.oauth: Manages Reddit's primary authentication method.
    • net.dean.jraw.pagination: Provides helpers for navigating paginated endpoints (e.g., subreddits or front page).
    • net.dean.jraw.ratelimit: Provides mechanisms to restrict request frequency to comply with API limits.
    • net.dean.jraw.references: Contains the basic building blocks of the JRAW API.
    • net.dean.jraw.tree: Specialized classes for handling comment trees.
    • net.dean.jraw.websocket: Provides helpers for WebSocket communication.
  2. Understand the JRAW Reference model

    master
    JRAW uses a fluent API built on Reference objects. A Reference is a lightweight, immutable, and abstract pointer to a Reddit resource (like a user, subreddit, or comment). A Reference does not guarantee that the resource exists; it simply represents the location of that resource. You create Reference objects starting from a RedditClient or by deriving them from other existing Reference objects.
  3. How JRAW handles JSON (de)serialization

    master

    JRAW uses OkHttp for HTTP requests and WebSocket connections, and Moshi for JSON (de)serialization.

    When consuming Reddit API data, you have three primary ways to handle the JSON structure:

    1. Map approach: Deserializing into a Map<String, Object>. This is easy but requires manual type casting and knowledge of exact JSON keys.
    2. Plain Object approach: Creating standard Java classes with @Json annotations. This provides type safety but requires significant boilerplate (getters, equals, hashCode, toString).
    3. AutoValue approach: Using Google's AutoValue library to generate boilerplate. This is the recommended way to handle the 30+ model classes used in JRAW.
  4. Use RedditClient to interact with the Reddit API

    master

    The RedditClient class is the central entry point for JRAW. It is responsible for:

    • Handling all HTTP requests.
    • Managing WebSocket connections.
    • Detecting errors within parsed JSON responses.

    RedditClient is the only class capable of sending requests to the Reddit API (with the exception of certain OAuth2 operations). All other classes that require network access or WebSocket connections do so through a RedditClient instance.

  5. Understand JRAW's default rate limiting behavior

    master

    By default, the RedditClient manages Reddit's OAuth2 API limit (60 requests per minute) using a conservative strategy. It allows one request per second with a 'burst' capacity of up to five requests at a time.

    Burst Behavior Example: If there has been no activity for at least five seconds and you suddenly trigger ten requests:

    1. The first five requests are sent immediately (the burst).
    2. The remaining five requests are throttled to a rate of one per second.

    This default behavior is designed to prevent hitting Reddit's denial threshold without requiring manual configuration.

  6. Use WebSockets for Live Thread updates

    master

    Instead of polling for updates using latestUpdates at a fixed interval, you can leverage WebSockets to receive real-time notifications when something happens to a live thread. This is more efficient for reacting to new content as it arrives.

    // Example of leveraging WebSockets for real-time updates
    LiveThreads.websocket(thread, (event) -> {
        // Handle real-time event
    });
  7. How the JRAW documentation system works

    master

    The JRAW documentation is a meta-project that generates Markdown files for hosting on GitBook. It uses a system of @CodeSample annotations and special syntax to ensure code samples in the documentation are always syntactically valid and up-to-date with the source code.

    Code Samples

    Code samples are defined in the net.dean.jraw.docs.samples package. Any method annotated with @CodeSample can be referenced in Markdown files.

    To include a code sample in a Markdown file (located in src/main/resources/content), use the following syntax:

    {{ @ClassName.methodName }}

    Note: A code sample must be the only thing on its line.

    Class Linking

    You can link directly to Javadoc for JRAW classes using the [[@ClassName]] syntax. This automatically generates a link to the corresponding HTML documentation.

    Note: For Enums, you must use the fully qualified class name (e.g., [[@com.example.MyEnum]]).

    // In net.dean.jraw.docs.samples
    final class Example {
        @CodeSample
        void showSomething() {
            String x = "foo";
            System.out.println(x);
        }
    }
    {{ @Example.showSomething }}
    
    Lorem ipsum [[@RedditClient]] sit amet.
  8. Choose the right Reddit OAuth2 app type

    master

    Reddit provides three types of OAuth2 apps. Choosing the correct one depends on where your code runs and whether it can keep a secret:

    • Web app: Runs on a server you control. It can keep a secret.
    • Installed app: Runs on devices you don't control (e.g., mobile phones). It cannot keep a secret and does not receive one.
    • Script app: Runs on hardware you control (e.g., your laptop). It can keep a secret and only has access to your own account.

    Additionally, Installed and Web apps can operate in "userless" (application-only) mode, which allows access to the API without requiring a specific user to authorize it.

  9. Renew access tokens

    master

    Access tokens expire after one hour. JRAW can refresh them automatically depending on your authentication method:

    • Automatic authentication: JRAW handles refreshing automatically without any extra configuration.
    • Interactive authentication: JRAW requires a refresh token to request new access tokens. To ensure you receive a refresh token, you must set requestRefreshToken to true when generating the authorization URL.
    • Manual renewal: If you disable automatic refreshing, you must manually trigger the refresh process.
    // Ensure refresh token is requested during interactive auth
    String url = authHelper.getAuthorizationUrl(true); // true = requestRefreshToken
  10. How pagination works in JRAW

    master

    Reddit API pagination is managed through the Listing structure. A Listing contains the data for a single page and the ID of the next model in the sequence.

    JRAW abstracts this complexity using Paginator objects. A Paginator tracks the last Listing received and manages the logic for requesting subsequent pages. There are two main types of paginators:

    1. Barebones: Only supports an explicit limit on the amount of data per page.
    2. Default: Supports a limit, sorting (e.g., top), and an optional time period (e.g., hour).

    Note that not all endpoints support sorting or time periods, so you must choose the paginator type compatible with your target endpoint.

  11. Handle Reddit API 'Envelopes' with @RedditModel

    master

    Most Reddit API responses are wrapped in an "envelope" structure, which typically looks like this:

    {
      "kind": "t2",
      "data": { ... }
    }

    In this structure, kind indicates the type of object (e.g., t2 for an account), and the actual object resides inside the data node.

    To allow JRAW to automatically unwrap these envelopes during deserialization, annotate your @AutoValue model classes with @RedditModel. This enables the use of the RedditModelAdapterFactory to map the contents of the data node directly to your class.

    @AutoValue
    @RedditModel
    abstract class Account {
        // ...
    }