JRAW Documentation
repository·master·Indexed 18 days ago
https://github.com/mattbdean/jrawA 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.
What's inside JRAW
- JRAW is a Reddit API wrapper designed for the JVM. It provides a simplified API for interacting with Reddit and includes built-in support for handling OAuth2 authentication. Although written in Kotlin, it is designed for use in both Kotlin and Java projects.
Overview of JRAW package structure
masterJRAW 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.
Understand the JRAW Reference model
masterJRAW uses a fluent API built onReferenceobjects. AReferenceis a lightweight, immutable, and abstract pointer to a Reddit resource (like a user, subreddit, or comment). AReferencedoes not guarantee that the resource exists; it simply represents the location of that resource. You createReferenceobjects starting from aRedditClientor by deriving them from other existingReferenceobjects.How JRAW handles JSON (de)serialization
masterJRAW 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:
- Map approach: Deserializing into a
Map<String, Object>. This is easy but requires manual type casting and knowledge of exact JSON keys. - Plain Object approach: Creating standard Java classes with
@Jsonannotations. This provides type safety but requires significant boilerplate (getters,equals,hashCode,toString). - AutoValue approach: Using Google's AutoValue library to generate boilerplate. This is the recommended way to handle the 30+ model classes used in JRAW.
- Map approach: Deserializing into a
Use RedditClient to interact with the Reddit API
masterThe
RedditClientclass is the central entry point for JRAW. It is responsible for:- Handling all HTTP requests.
- Managing WebSocket connections.
- Detecting errors within parsed JSON responses.
RedditClientis 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 aRedditClientinstance.Understand JRAW's default rate limiting behavior
masterBy default, the
RedditClientmanages 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:
- The first five requests are sent immediately (the burst).
- 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.
Use WebSockets for Live Thread updates
masterInstead of polling for updates using
latestUpdatesat 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 });How the JRAW documentation system works
masterThe JRAW documentation is a meta-project that generates Markdown files for hosting on GitBook. It uses a system of
@CodeSampleannotations 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.samplespackage. Any method annotated with@CodeSamplecan 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.Choose the right Reddit OAuth2 app type
masterReddit 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.
Renew access tokens
masterAccess 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
requestRefreshTokentotruewhen 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 = requestRefreshTokenHow pagination works in JRAW
masterReddit API pagination is managed through the
Listingstructure. AListingcontains the data for a single page and the ID of the next model in the sequence.JRAW abstracts this complexity using
Paginatorobjects. APaginatortracks the lastListingreceived and manages the logic for requesting subsequent pages. There are two main types of paginators:- Barebones: Only supports an explicit limit on the amount of data per page.
- 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.
Handle Reddit API 'Envelopes' with @RedditModel
masterMost Reddit API responses are wrapped in an "envelope" structure, which typically looks like this:
{ "kind": "t2", "data": { ... } }In this structure,
kindindicates the type of object (e.g.,t2for an account), and the actual object resides inside thedatanode.To allow JRAW to automatically unwrap these envelopes during deserialization, annotate your
@AutoValuemodel classes with@RedditModel. This enables the use of theRedditModelAdapterFactoryto map the contents of thedatanode directly to your class.@AutoValue @RedditModel abstract class Account { // ... }