0 Day Analytics – REST API Module Developer Documentation

Table of Contents

1. Overview & Architecture

The REST API Module provides comprehensive management and security controls for all WordPress REST API endpoints. It discovers every registered route, presents them in a filterable admin list table, and allows administrators to disable endpoints, restrict specific HTTP methods, and obfuscate routes from the REST API discovery index.

Key Capabilities

  • Automatically discover all registered REST API endpoints and their metadata
  • Completely disable any endpoint (returns 403 Forbidden)
  • Selectively disable specific HTTP methods per endpoint
  • Obfuscate endpoints from REST API index/discovery responses without disabling them
  • Detect public vs. protected endpoints (authentication requirements)
  • Filter, sort, search, and paginate the endpoint list
  • Bulk enable/disable operations
  • CSV export with applied filters and batched processing
  • Dynamic route pattern matching (handles parameterised routes)

Technology Stack

  • PHP 7.4+ (strict types)
  • WordPress WP_List_Table API
  • WordPress REST API hooks (rest_pre_dispatch, rest_index, rest_namespace_index)
  • WordPress Options API for rule storage
  • AJAX-based CSV export with progress tracking

2. File Map

advanced-analytics/
└─ classes/
    └── vendor/
        ├── helpers/
        │   └── class-rest-api-helper.php       — Endpoint discovery, rules storage & enforcement
        ├── lists/
        │   ├── class-rest-api-list.php         — WP_List_Table for endpoints
        │   └── views/
        │       └── class-rest-api-view.php     — Page rendering & form handlers
        └── settings/
            └── settings-options/
                └── rest-api.php                — Module settings fields

3. Admin Screens

3.1 Endpoints List

URL wp-admin/admin.php?page=advan_rest_api
Menu Position Sub-menu under “Error Logs” (position 13)
Capability manage_options
Controller Rest_Api_View::analytics_rest_api_page()
List Table Rest_Api_List (extends Abstract_List / WP_List_Table)

UI Components

  • Summary bar — Total endpoints, disabled count, obfuscated count
  • Filter dropdowns — Namespace, Method, Status, Access
  • Search box — Searches route and namespace
  • Sortable columns — Route, Namespace, Status
  • Row actions — Edit | Enable/Disable
  • Bulk actions — Disable | Enable
  • CSV Export button with progress bar

Screen layout:

┌──────────────────────────────────────────────────────────────────┐
│  REST API Endpoints                                              │
│──────────────────────────────────────────────────────────────────│
│  Summary: 156 total | 3 disabled | 2 obfuscated                  │
│──────────────────────────────────────────────────────────────────│
│  [Namespace ▼] [Method ▼] [Status ▼] [Access ▼] [Filter]         │
│  [CSV Export]                                    [🔍 Search]     │
│──────────────────────────────────────────────────────────────────│
│  ☐ Endpoint Route ↕   | Methods     | Namespace | In Index | …   │
│  ☐ /wp/v2/posts        | GET POST    | wp/v2     | ✔        | …  │
│     Edit | Disable                                               │
│  ☐ /wp/v2/users 🚫     | GET POST DEL| wp/v2     | ✔        | …  │
│     Edit | Enable                                                │
│──────────────────────────────────────────────────────────────────│
│  Bulk Actions [▼] [Apply]                        ‹ 1 of 4 ›      │
└──────────────────────────────────────────────────────────────────┘

3.2 Edit Endpoint

URL wp-admin/admin.php?page=advan_rest_api&action=edit_route&route_hash={hash}&_wpnonce={nonce}
Form Action admin_post_advan_rest_api_save
Handler Rest_Api_View::save_endpoint_rules()
Nonce advana_rest_api_manager (field: _advan_rest_api_nonce)

Form Fields

Field Type Name Description
Route Hash hidden route_hash First 12 characters of MD5 hash of the route
Disable Endpoint Entirely checkbox disable_endpoint Blocks all requests with 403 Forbidden
Disable Specific Methods checkboxes disabled_methods[] Array of HTTP methods to disable individually
Obfuscate Endpoint checkbox obfuscate_endpoint Hides endpoint from REST API index discovery

3.3 Module Settings

URL wp-admin/admin.php?page=advan_logs_settings#aadvana-options-tab-rest-api
Settings File classes/vendor/settings/settings-options/rest-api.php

Available Settings

Setting ID Type Description
Enable REST API module rest_api_module_enabled checkbox Enables/disables the REST API management module. When disabled, all enforcement hooks are removed and endpoints become accessible. The admin menu is hidden.

4. Core Classes

4.1 ADVAN\Helpers\Rest_Api_Helper

The core service class responsible for endpoint discovery, rule storage, and runtime enforcement. All methods are static.

Constants

PHP
<?php
private const OPTION_NAME = ADVAN_PREFIX . 'rest_api_rules';
// Resolves to: aadvana_rest_api_rules

Static Properties

Property Type Description
$rules_cache array|null In-memory cache of endpoint rules (cleared on save)
$endpoints_cache array|null In-memory cache of discovered endpoints

Public Methods

Method Return Description
init() void Registers the three enforcement hooks: rest_pre_dispatch, rest_index, rest_namespace_index
enforce_endpoint_rules($result, $server, $request) mixed|WP_Error Hooked at priority 0 on rest_pre_dispatch. Returns 403 for disabled endpoints/methods
filter_rest_index($response) WP_REST_Response Hooked at PHP_INT_MAX on rest_index. Removes obfuscated/disabled routes from the index
filter_namespace_index($response, $request) WP_REST_Response Hooked at PHP_INT_MAX on rest_namespace_index. Removes hidden routes from namespace indexes
get_all_endpoints() array Returns all registered REST API endpoints with metadata. Uses rest_get_server() internally
get_all_namespaces() array Returns sorted, unique list of all endpoint namespaces
get_all_methods() array Returns sorted, unique list of all HTTP methods across all endpoints
get_endpoint_rules() array Retrieves rules from database with validation. Cached in memory
save_endpoint_rules(array $rules) bool Validates, sanitises, and saves rules. Clears cache

Private Methods

Method Return Description
route_to_regex(string $route) string|false Converts REST route patterns (e.g. /wp/v2/posts/(?P<id>[\d]+)) to anchored regex for matching

4.2 ADVAN\Lists\Rest_Api_List

Extends Abstract_List (which extends WP_List_Table). Handles the admin list table rendering, column management, filtering, sorting, bulk actions, and CSV export.

Constants

PHP
<?php
public const PAGE_SLUG            = ADVAN_INNER_SLUG . '_page_advan_rest_api';
public const SCREEN_OPTIONS_SLUG  = 'advanced_analytics_rest_api_list';
public const SEARCH_INPUT         = 's';
public const MENU_SLUG            = 'advan_rest_api';
public const REST_API_MENU_SLUG   = 'advan_rest_api';
public const NONCE_NAME           = 'advana_rest_api_manager';
public const SAVE_ACTION          = 'advan_rest_api_save';
public const TOGGLE_ACTION        = 'advan_rest_api_toggle';

Static Methods

Method Return Description
hooks_init() void Registers admin actions for styles, save, and toggle handlers
menu_add() void Adds the REST API sub-menu page, screen options, and column filters
manage_columns($columns) array Defines table columns: cb, route, methods, namespace, show_in_index, is_public, status
format_column_value($item, $column_name) string Formats column display values with badges, icons, and colour coding
process_bulk_actions() void Handles bulk disable/enable on the load-{page} hook
get_preserved_list_params() array Returns current filter/sort/page state for URL preservation across redirects
get_filtered_endpoints_for_export(array $args) array Returns filtered, paginated rows for batched CSV export

Instance Methods

Method Description
get_sortable_columns() Returns sortable columns: route, namespace, status
get_bulk_actions() Returns bulk actions: disable, enable
prepare_items() Fetches endpoints, applies 5 filter types, sorts, and paginates
extra_tablenav($which) Renders filter dropdowns and CSV export button
column_route($item) Route column with edit/toggle row actions and obfuscate badge
column_cb($item) Checkbox column for bulk selection

HTTP Method Colour Codes

Method Colour Hex
GET Green #00a32a
POST Blue #2271b1
PUT / PATCH Orange #dba617
DELETE Red #d63638
OPTIONS / HEAD Grey #8c8f94

4.3 ADVAN\Lists\Views\Rest_Api_View

Extends Abstract_View. Handles page rendering and form processing for the REST API admin screens.

Public Methods

Method Return Description
analytics_rest_api_page() void Main entry point. Calls display_page() with permission check
save_endpoint_rules() void Handles edit form submission. Verifies nonce, validates input, saves rules, redirects
toggle_endpoint() void Handles quick enable/disable toggle from row actions

Private Methods

Method Description
render_page_content() Routes to list or edit view based on action parameter
render_list_page() Renders summary bar, filters, list table, and CSV export UI
render_edit_page() Renders edit form with disable, method, and obfuscate options
get_method_color(string $method) Returns hex colour code for an HTTP method badge

5. Data Model & Storage

The REST API module does not use a custom database table. Rules are stored in the WordPress wp_options table.

Database Option

Option Name aadvana_rest_api_rules
Autoload no (passed as third argument to update_option)
Format Serialised PHP array

Rule Data Structure

PHP
<?php
// Stored structure: route pattern => rule configuration
$rules = array(
    '/wp/v2/posts' => array(
        'disabled'         => true,              // Fully disable endpoint
        'disabled_methods' => array( 'DELETE' ),  // Disable specific methods only
        'obfuscate'        => true,              // Hide from REST index
    ),
    '/wp/v2/users/(?P<id>[\d]+)' => array(
        'disabled_methods' => array( 'PUT', 'PATCH', 'DELETE' ),
    ),
);

Endpoint Data Structure

Returned by Rest_Api_Helper::get_all_endpoints():

PHP
<?php
$endpoint = array(
    'route'         => '/wp/v2/posts',
    'route_hash'    => 'abc123def456',  // First 12 chars of MD5 hash
    'methods'       => array( 'GET', 'POST' ),
    'namespace'     => 'wp/v2',
    'show_in_index' => true,
    'is_public'     => false,  // true if no permission_callback or __return_true
    'status'        => 'active', // active | disabled | partial
);

CSV Export Row Structure

PHP
<?php
$csv_row = array(
    'Route'    => '/wp/v2/posts',
    'Methods'  => 'GET, POST',
    'Namespace'=> 'wp/v2',
    'In Index' => 'Yes',
    'Access'   => 'Protected',
    'Status'   => 'Active',
);

6. Runtime Execution Flow

Initialisation Flow

TEXT
advanced-analytics.php
├─ Check if rest_api_module_enabled setting is on
├─ Call Rest_Api_Helper::init()
│  └─ Register hooks:
│     ├─ rest_pre_dispatch (priority 0)     — enforcement
│     ├─ rest_index (priority PHP_INT_MAX)  — obfuscation
│     └─ rest_namespace_index (PHP_INT_MAX) — namespace filtering
├─ plugins_loaded
│  └─ Advanced_Analytics::init()
│     └─ If module enabled:
│        └─ Rest_Api_List::menu_add()      — admin menu
└─ admin_init
   └─ Rest_Api_List::hooks_init()          — admin actions

REST Request Interception Flow

TEXT
Incoming REST Request → /wp-json/wp/v2/posts
├─ rest_pre_dispatch fires (priority 0)
│  └─ Rest_Api_Helper::enforce_endpoint_rules()
│     ├─ Load rules from options (cached)
│     ├─ Match route: exact match first, then regex pattern match
│     ├─ If endpoint fully disabled:
│     │  └─ Return WP_Error (403 "rest_endpoint_disabled")
│     └─ If specific method disabled:
│        └─ Return WP_Error (403 "rest_method_disabled")
├─ If no rule matches → process request normally
└─ On response:
   └─ rest_index / rest_namespace_index fires
      └─ Remove obfuscated/disabled routes from discovery data

Rule Save Flow

TEXT
User clicks "Save Changes" on edit page
├─ Form POST to admin-post.php
├─ admin_post_advan_rest_api_save fires
└─ Rest_Api_View::save_endpoint_rules()
   ├─ Verify nonce (_advan_rest_api_nonce / advana_rest_api_manager)
   ├─ Check manage_options capability
   ├─ Find endpoint by route_hash
   ├─ Build rule array from POST data:
   │  ├─ disable_endpoint → disabled flag
   │  ├─ disabled_methods[] → disabled_methods array
   │  └─ obfuscate_endpoint → obfuscate flag
   ├─ Call Rest_Api_Helper::save_endpoint_rules()
   │  ├─ Validate rule structure
   │  ├─ Filter to valid HTTP methods only
   │  ├─ Remove empty rules
   │  ├─ Save to wp_options
   │  └─ Clear internal cache
   └─ Redirect back to edit page with &updated=true

7. Hooks & Filters

WordPress REST API Filters (registered by Rest_Api_Helper::init())

Hook Type Priority Callback Description
rest_pre_dispatch Filter 0 Rest_Api_Helper::enforce_endpoint_rules() Enforces disable/method rules. Returns 403 WP_Error for blocked requests
rest_index Filter PHP_INT_MAX Rest_Api_Helper::filter_rest_index() Removes obfuscated and disabled routes from the main REST API index (/wp-json/)
rest_namespace_index Filter PHP_INT_MAX Rest_Api_Helper::filter_namespace_index() Removes hidden routes from namespace-specific index responses

Admin Action Hooks

Hook Type Callback Description
admin_post_advan_rest_api_save Action Rest_Api_View::save_endpoint_rules() Handles edit form submission for endpoint rule updates
admin_post_advan_rest_api_toggle Action Rest_Api_View::toggle_endpoint() Handles quick enable/disable toggle from row actions
admin_print_styles-{page_slug} Action Settings::print_styles() Enqueues admin styles for the REST API page
load-{page_slug} Action Rest_Api_List::process_bulk_actions() Processes bulk enable/disable actions before page output
load-{page_slug} Action Settings::aadvana_common_help() Sets up contextual help tab
manage_{page_slug}_columns Filter Rest_Api_List::manage_columns() Defines list table columns

8. Settings Reference

Setting ID Type Default Description
rest_api_module_enabled checkbox unchecked (disabled) Master toggle for the REST API module. Controls menu visibility and all enforcement hooks

Database Options

Option Name Format Description
aadvana_rest_api_rules Serialised array Stores all endpoint rules (disable, method restrictions, obfuscation)

9. List Table Columns & Sorting

Column ID Label Sortable Rendering
cb Checkbox No Bulk selection checkbox
route Endpoint Route Yes Route <code> tag + obfuscate icon + row actions
methods Methods No Colour-coded badges; disabled methods shown with strikethrough
namespace Namespace Yes Namespace in <code> tag
show_in_index In Index No Dashicons checkmark (green) or dismiss (red)
is_public Public No “Public” (orange, warning icon) or “Protected” (green, lock icon)
status Status Yes “Active” (green) / “Disabled” (red) / “Partial” (orange)

Filter Parameters (preserved across page navigation)

Parameter Type Description
s string Search text (matches route and namespace)
namespace_filter string Filter by namespace
status_filter string Filter by status: active or disabled
method_filter string Filter by HTTP method
access_filter string Filter by access level: public or protected
orderby string Sort column: route, namespace, or status
order string Sort direction: asc or desc
paged int Current page number

10. Bulk & Row Actions

Bulk Actions

Action Nonce Handler Effect
Disable bulk-items Rest_Api_List::process_bulk_actions() Sets disabled = true for each selected route
Enable bulk-items Rest_Api_List::process_bulk_actions() Removes disabled flag; cleans up empty rule entries

Row Actions

Action URL Pattern Handler
Edit admin.php?page=advan_rest_api&action=edit_route&route_hash={hash} Rest_Api_View::render_edit_page()
Enable / Disable admin-post.php?action=advan_rest_api_toggle&route_hash={hash}&toggle={enable|disable} Rest_Api_View::toggle_endpoint()

11. CSV Export

CSV export uses the shared AJAX export infrastructure in Ajax_Helper.

AJAX Request

Action advan_export_list_data (POST)
Type Export rest_api
Batch Size 500 (default)

Request Parameters

Parameter Description
typeExport Must be rest_api
batch Current batch number (1-based)
batch_size Items per batch
search Search filter text
namespace_filter Namespace filter value
status_filter Status filter value
method_filter Method filter value
access_filter Access filter value

The export delegates to Rest_Api_List::get_filtered_endpoints_for_export() which applies the same filtering logic as the list table.

12. Code Examples

12.1 Programmatically Disable an Endpoint

PHP
<?php
use ADVAN\Helpers\Rest_Api_Helper;

// Disable the users endpoint entirely.
$rules = Rest_Api_Helper::get_endpoint_rules();
$rules['/wp/v2/users'] = array(
    'disabled' => true,
);
Rest_Api_Helper::save_endpoint_rules( $rules );

12.2 Disable Specific Methods on an Endpoint

PHP
<?php
use ADVAN\Helpers\Rest_Api_Helper;

// Allow GET but block POST, PUT, PATCH, DELETE on /wp/v2/posts.
$rules = Rest_Api_Helper::get_endpoint_rules();
$rules['/wp/v2/posts'] = array(
    'disabled_methods' => array( 'POST', 'PUT', 'PATCH', 'DELETE' ),
);
Rest_Api_Helper::save_endpoint_rules( $rules );

12.3 Obfuscate an Endpoint

PHP
<?php
use ADVAN\Helpers\Rest_Api_Helper;

// Hide /wp/v2/users from the REST API index but keep it functional.
$rules = Rest_Api_Helper::get_endpoint_rules();
$rules['/wp/v2/users'] = array(
    'obfuscate' => true,
);
Rest_Api_Helper::save_endpoint_rules( $rules );

12.4 Combine Multiple Rules

PHP
<?php
use ADVAN\Helpers\Rest_Api_Helper;

// Obfuscate AND restrict DELETE on /wp/v2/posts.
$rules = Rest_Api_Helper::get_endpoint_rules();
$rules['/wp/v2/posts'] = array(
    'disabled_methods' => array( 'DELETE' ),
    'obfuscate'        => true,
);
Rest_Api_Helper::save_endpoint_rules( $rules );

12.5 List All Public Endpoints

PHP
<?php
use ADVAN\Helpers\Rest_Api_Helper;

// Get all endpoints and filter to those with no authentication requirement.
$all_endpoints = Rest_Api_Helper::get_all_endpoints();
$public = array_filter( $all_endpoints, function ( $ep ) {
    return ! empty( $ep['is_public'] );
} );

foreach ( $public as $ep ) {
    printf(
        "Route: %s | Methods: %s | Namespace: %s\n",
        $ep['route'],
        implode( ', ', $ep['methods'] ),
        $ep['namespace']
    );
}

12.6 Disable All Endpoints in a Namespace

PHP
<?php
use ADVAN\Helpers\Rest_Api_Helper;

// Disable every endpoint under the "custom-plugin/v1" namespace.
$all_endpoints = Rest_Api_Helper::get_all_endpoints();
$rules         = Rest_Api_Helper::get_endpoint_rules();

foreach ( $all_endpoints as $ep ) {
    if ( 'custom-plugin/v1' === $ep['namespace'] ) {
        $rules[ $ep['route'] ] = array( 'disabled' => true );
    }
}

Rest_Api_Helper::save_endpoint_rules( $rules );

12.7 Re-enable All Disabled Endpoints

PHP
<?php
use ADVAN\Helpers\Rest_Api_Helper;

// Clear all rules — re-enables everything.
Rest_Api_Helper::save_endpoint_rules( array() );

12.8 Check if an Endpoint is Disabled

PHP
<?php
use ADVAN\Helpers\Rest_Api_Helper;

$rules = Rest_Api_Helper::get_endpoint_rules();
$route = '/wp/v2/users';

if ( isset( $rules[ $route ]['disabled'] ) && $rules[ $route ]['disabled'] ) {
    echo 'Endpoint is fully disabled.';
} elseif ( ! empty( $rules[ $route ]['disabled_methods'] ) ) {
    echo 'Partially restricted. Disabled methods: '
        . implode( ', ', $rules[ $route ]['disabled_methods'] );
} else {
    echo 'Endpoint is fully active.';
}

12.9 Public / Protected Endpoint Detection Logic

The module determines whether an endpoint is public (no authentication required) using the following logic from the WordPress route handlers:

PHP
<?php
// An endpoint is considered public if ANY of its handlers meets these criteria:
$is_public = ! isset( $handler['permission_callback'] )
    || empty( $handler['permission_callback'] )
    || '__return_true' === $handler['permission_callback'];

12.10 Dynamic Route Pattern Matching

REST API routes can contain regex parameters (e.g. /wp/v2/posts/(?P<id>[\d]+)). The enforcement engine converts these patterns to anchored regular expressions for matching:

PHP
<?php
// A stored rule for the pattern:
// /wp/v2/posts/(?P<id>[\d]+)
//
// Will match requests to:
// /wp/v2/posts/42
// /wp/v2/posts/123
//
// The conversion uses:
$regex = '#^' . $route_pattern . '$#';
// e.g. #^/wp/v2/posts/(?P<id>[\d]+)$#

Need User Guide documentation?
See REST API User Guide for more details about configuration, practical usage and information.

← REST API Module — User Guide WP Panel Module – User Guide →
Share this page
Back to top