wp-rest-api

Scaffolds and reviews custom WordPress REST API endpoints registered via register_rest_route on rest_api_init — namespace and version slug, permission_callback authorization (NEVER __return_true on state-changing routes, which is the most common plugin-side vulnerability on wp.org), args schema with validate_callback / sanitize_callback / type / enum, object-level capability checks via current_user_can with object ID, responses with WP_REST_Response and WP_Error carrying an HTTP status, no raw DB rows / sensitive columns in responses, cookie auth via X-WP-Nonce, REST vs admin-ajax decision. Recommends the better-route library when the plugin grows past a few endpoints. Use when scaffolding or reviewing a REST endpoint, or migrating from admin-ajax. Triggers on register_rest_route, rest_api_init, permission_callback, WP_REST_Request, WP_REST_Response, WP_Error, X-WP-Nonce, rest_ensure_response, register_rest_field, or any file path containing /rest/ or /api/ in a WP plugin or theme.

Best use case

wp-rest-api is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Scaffolds and reviews custom WordPress REST API endpoints registered via register_rest_route on rest_api_init — namespace and version slug, permission_callback authorization (NEVER __return_true on state-changing routes, which is the most common plugin-side vulnerability on wp.org), args schema with validate_callback / sanitize_callback / type / enum, object-level capability checks via current_user_can with object ID, responses with WP_REST_Response and WP_Error carrying an HTTP status, no raw DB rows / sensitive columns in responses, cookie auth via X-WP-Nonce, REST vs admin-ajax decision. Recommends the better-route library when the plugin grows past a few endpoints. Use when scaffolding or reviewing a REST endpoint, or migrating from admin-ajax. Triggers on register_rest_route, rest_api_init, permission_callback, WP_REST_Request, WP_REST_Response, WP_Error, X-WP-Nonce, rest_ensure_response, register_rest_field, or any file path containing /rest/ or /api/ in a WP plugin or theme.

Teams using wp-rest-api should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/wp-rest-api/SKILL.md --create-dirs "https://raw.githubusercontent.com/nvdigitalsolutions/mcp-ai-wpoos/main/.agents/skills/wp-rest-api/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/wp-rest-api/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How wp-rest-api Compares

Feature / Agentwp-rest-apiStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Scaffolds and reviews custom WordPress REST API endpoints registered via register_rest_route on rest_api_init — namespace and version slug, permission_callback authorization (NEVER __return_true on state-changing routes, which is the most common plugin-side vulnerability on wp.org), args schema with validate_callback / sanitize_callback / type / enum, object-level capability checks via current_user_can with object ID, responses with WP_REST_Response and WP_Error carrying an HTTP status, no raw DB rows / sensitive columns in responses, cookie auth via X-WP-Nonce, REST vs admin-ajax decision. Recommends the better-route library when the plugin grows past a few endpoints. Use when scaffolding or reviewing a REST endpoint, or migrating from admin-ajax. Triggers on register_rest_route, rest_api_init, permission_callback, WP_REST_Request, WP_REST_Response, WP_Error, X-WP-Nonce, rest_ensure_response, register_rest_field, or any file path containing /rest/ or /api/ in a WP plugin or theme.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# WordPress REST API: scaffold, review, secure

For WordPress 4.7+ REST endpoints registered via `register_rest_route()`. This skill covers the full lifecycle of a custom endpoint — registration, authorization, input validation, response shaping, error handling — and the patterns that distinguish a clean endpoint from one that ships a vulnerability.

This is the **default** path for new server endpoints in modern WordPress. Use REST instead of `admin-ajax` unless you have a concrete reason (legacy interop, Heartbeat, etc.).

## When to use this skill

Trigger when ANY of the following is true:

- Scaffolding a new REST endpoint or reviewing one in a PR.
- The diff or file contains: `register_rest_route`, `rest_api_init`, `WP_REST_Request`, `WP_REST_Response`, `WP_Error`, `permission_callback`, `register_rest_field`, `rest_ensure_response`, `X-WP-Nonce`.
- The user is migrating an `admin-ajax` handler to REST, or asking which to use.
- The user is debugging a `401`, `403`, or "Sorry, you are not allowed to do that" response.
- The plugin is going headless / mobile / external-integration heavy and needs a stable API contract.

## Architecture in one paragraph

Every REST endpoint is a `(namespace, route, method)` triple registered on `rest_api_init`. WP routes the request through `WP_REST_Server::dispatch()`, which runs `WP_REST_Request::has_valid_params()` (validate) and `WP_REST_Request::sanitize_params()` (sanitize) FIRST, then calls your `permission_callback` (returning `true` / `false` / `WP_Error`), then your `callback`. The callback returns a `WP_REST_Response` for success or a `WP_Error` for failure. Cookie-authenticated requests must include a `_wpnonce` query param or `X-WP-Nonce` header (the `wp-api` nonce, generated via `wp_create_nonce('wp_rest')`); other auth schemes — application passwords, OAuth, JWT — bypass the nonce.

**Order matters for security.** Because validation and sanitization run BEFORE the permission check, never put expensive lookups, DB writes, or other side effects inside a `validate_callback` / `sanitize_callback`. They run for unauthenticated requests too. Reserve those for the main `callback`, which only runs after permission has been granted.

## Workflow — minimal scaffold

```php
add_action( 'rest_api_init', static function (): void {
    register_rest_route(
        'myplugin/v1',
        '/items/(?P<id>\d+)',
        array(
            'methods'             => WP_REST_Server::READABLE, // 'GET'
            'callback'            => 'myplugin_get_item',
            'permission_callback' => static function ( WP_REST_Request $request ) {
                return current_user_can( 'read_post', (int) $request['id'] );
            },
            'args'                => array(
                'id' => array(
                    'required'          => true,
                    'type'              => 'integer',
                    'validate_callback' => static fn( $v ) => is_numeric( $v ) && (int) $v > 0,
                    'sanitize_callback' => 'absint',
                ),
            ),
        )
    );
} );

/**
 * @return WP_REST_Response|WP_Error
 */
function myplugin_get_item( WP_REST_Request $request ) {
    $id   = (int) $request['id'];
    $post = get_post( $id );

    if ( ! $post ) {
        return new WP_Error(
            'myplugin_not_found',
            __( 'Item not found.', 'myplugin' ),
            array( 'status' => 404 )
        );
    }

    return rest_ensure_response( array(
        'id'    => $post->ID,
        'title' => get_the_title( $post ),
    ) );
}
```

That snippet contains every required moving part — namespace + version, route with named param, method constant, `permission_callback`, `args` schema, response via `rest_ensure_response`, error via `WP_Error` with `status` data.

## Critical rules

### 1. `permission_callback` is REQUIRED, and `__return_true` is rarely correct

The single most common plugin-side vulnerability on wp.org. Rules:

- **NEVER** use `'permission_callback' => '__return_true'` on a route that writes (POST / PUT / PATCH / DELETE). It means "any unauthenticated visitor can call this".
- **Only acceptable** for genuinely public read-only routes (e.g. site status, public catalog). Even then, document the choice with a comment and consider rate limiting.
- For state-changing routes, check at minimum a capability (`current_user_can('edit_posts')`) and ideally an object-level cap with the target ID:
  ```php
  'permission_callback' => fn( $req ) => current_user_can( 'edit_post', (int) $req['id'] ),
  ```
- When `permission_callback` returns `false` / `null`, WP wraps it in a `rest_forbidden` `WP_Error` whose status comes from `rest_authorization_required_code()` — that returns **401 if the user is logged out, 403 if logged in but unauthorized**. Returning a custom `WP_Error` with explicit `status` lets you control the code and the message; `false` is fine when the default is correct for your route.

### 2. Always declare an `args` schema

Each accepted parameter (URL, query string, body) needs an `args` entry. Otherwise input lands raw in `$request->get_param()` — no validation, no sanitization.

```php
'args' => array(
    'email' => array(
        'required'          => true,
        'type'              => 'string',
        'format'            => 'email',
        'validate_callback' => 'is_email',
        'sanitize_callback' => 'sanitize_email',
    ),
    'role' => array(
        'required'          => false,
        'type'              => 'string',
        'enum'              => array( 'subscriber', 'contributor', 'author' ),
        'default'           => 'subscriber',
    ),
    'count' => array(
        'type'              => 'integer',
        'minimum'           => 1,
        'maximum'           => 100,
        // No custom sanitize_callback — when 'type' is set and no callback
        // is given, WP defaults to rest_parse_request_arg, which runs both
        // schema validation (minimum/maximum/enum/type) AND sanitization.
        // The moment you set your own sanitize_callback, that default is
        // replaced and the schema constraints become documentation only —
        // unless you also set 'validate_callback' => 'rest_validate_request_arg'.
    ),
),
```

`validate_callback` returns `true` / `false` / `WP_Error`. `sanitize_callback` runs after validation. Use built-ins (`absint`, `sanitize_text_field`, `sanitize_email`, `sanitize_key`, `rest_sanitize_boolean`) where possible — but if you set a custom `sanitize_callback`, ALSO set `'validate_callback' => 'rest_validate_request_arg'` (or your own validator) so schema constraints actually run. Otherwise `'minimum' => 1, 'maximum' => 100` is silently ignored.

### 3. Read input through `$request`, not `$_POST` / `$_GET`

`$request->get_param('foo')` returns the parameter from URL, query, or body, **already unslashed and run through your sanitize_callback**. Don't read superglobals inside REST callbacks — you bypass the schema.

For JSON bodies specifically: `$request->get_json_params()` returns the decoded array. WP also reads multipart and form-encoded automatically.

### 4. Return `WP_REST_Response` or `WP_Error`, never `wp_send_json_*`

`wp_send_json_*` is for `admin-ajax`. In REST, return objects:

```php
return rest_ensure_response( $data );        // 200 OK with $data as JSON
return new WP_REST_Response( $data, 201 );   // explicit status
return new WP_Error( 'code', 'message', array( 'status' => 422 ) ); // error
```

`WP_Error` codes should be namespaced (`myplugin_validation_failed`, not `validation_failed`). Status codes follow HTTP semantics: `400` validation, `401` unauthenticated, `403` forbidden, `404` not found, `409` conflict, `422` semantic validation, `500` server error.

### 5. Don't leak sensitive columns

Never return raw `$wpdb->get_results()` rows — they contain `user_pass`, `user_activation_key`, internal meta. Build response objects explicitly:

```php
// WRONG — leaks user_pass and other private columns
return rest_ensure_response( $wpdb->get_row( ... ) );

// RIGHT — explicit allowlist
return rest_ensure_response( array(
    'id'    => (int) $user->ID,
    'name'  => $user->display_name,
    'email' => $user->user_email,
) );
```

### 6. Meta capabilities need the object ID

```php
// WRONG — meta cap without object: result is unreliable / not what you think
current_user_can( 'edit_post' )

// RIGHT — meta cap mapped to a specific object via map_meta_cap()
current_user_can( 'edit_post', $post_id )
```

`edit_post` / `delete_post` / `read_post` / `edit_user` etc. are **meta capabilities** — WP's `map_meta_cap()` resolves them to primitive caps PLUS object-ownership rules using the ID. Without the ID, the resolution is unreliable (it may pass for users who shouldn't have access to that specific object, or fail for ones who should). For any object-level route — single post, single user, single order, single subscription — always pass the relevant ID as the second argument.

### 7. Cookie-authenticated requests need a nonce

Browser-side requests using cookie auth need `_wpnonce` (query) or `X-WP-Nonce` (header) with the value from `wp_create_nonce('wp_rest')`. The official `@wordpress/api-fetch` package adds this automatically; manual `fetch()` calls must add it themselves.

```js
fetch( '/wp-json/myplugin/v1/items/42', {
    method: 'POST',
    credentials: 'include',
    headers: {
        'Content-Type': 'application/json',
        'X-WP-Nonce': wpApiSettings.nonce, // localized via wp_localize_script
    },
    body: JSON.stringify( { ... } ),
} );
```

The official `@wordpress/api-fetch` package adds the nonce automatically **only inside the WordPress admin / block editor**, where WP localizes `wpApiSettings.nonce` and api-fetch reads it. In a **decoupled frontend** (headless app, public-site SPA, mobile client), you must set the nonce yourself — or use a different auth scheme entirely (Application Passwords, OAuth, JWT). Application passwords, OAuth, JWT don't need the nonce at all; the `Authorization` header itself carries the proof.

### 8. Treat the version segment as mandatory

`/myplugin/v1/items` — the `v1` is not enforced by WP at runtime, but treat it as a project policy. When you need a breaking change, ship `v2` alongside, deprecate `v1`, and remove it after a long migration window. NEVER change the contract of an existing versioned route — clients in the wild won't know.

## Common mistakes

```php
// WRONG — public write endpoint
register_rest_route( 'myplugin/v1', '/save', array(
    'methods'             => 'POST',
    'callback'            => 'save_thing',
    'permission_callback' => '__return_true', // 🔥 anyone can write
) );

// WRONG — no args schema, raw input
function save_thing( WP_REST_Request $req ) {
    $title = $req['title'];                    // not validated, not sanitized
    $body  = $_POST['body'];                   // bypasses REST entirely
    update_post_meta( $req['id'], 'thing', $req['payload'] ); // mass assignment
}

// WRONG — leaks DB row
return $wpdb->get_row( "SELECT * FROM ..." );

// WRONG — uses admin-ajax response in a REST callback
wp_send_json_success( $data );  // function returns null, REST sees void
exit;                            // murders the rest of the request lifecycle
```

If you see any of these in a PR, block it and point at the correct pattern.

## REST vs admin-ajax — when to use which

| Use REST when | Use admin-ajax when |
|---|---|
| New endpoint, post-WP 4.7 | Maintaining an existing `wp_ajax_*` handler |
| Mobile / external clients call it | Internal admin-only AJAX inside a settings screen the rest of the WP admin already has |
| You need a versioned, documented contract | Heartbeat-style polling tied to the WP admin lifecycle |
| Headless / SPA frontend | Quick prototype that won't outgrow the codebase |

There is **no security argument** for `admin-ajax` over REST — both need their own nonce + capability story. The REST nonce (`wp_rest`) and capability (`permission_callback`) are simply better factored.

## Multi-route plugins — graduate to better-route

If a plugin grows beyond ~3-5 endpoints and especially if it goes headless / integration-heavy, the raw `register_rest_route` boilerplate becomes painful: manual auth wiring on every route, inconsistent error payloads, no middleware, no idempotency, no ETag, no metrics.

For this exact case there is **better-route** — a fluent REST routing and resource library for WP, PHP 8.1+. **It is a library, not a WordPress plugin** — installed only via Composer through a VCS repository (not on Packagist). Pin the constraint to the latest tag in the repo:

```json
{
    "require": {
        "better-route/better-route": "^0.3.0"
    },
    "repositories": [
        {
            "type": "vcs",
            "url": "https://github.com/Lonsdale201/better-route"
        }
    ],
    "prefer-stable": true
}
```

(The example pins `^0.3.0` — check the repo's install docs for the current stable tag, the constraint string evolves with the library.)

What it gives over raw `register_rest_route`:

- Fluent router with grouping (`Router::make('myplugin', 'v1')->get(...)->post(...)`).
- Middleware pipeline (`global -> group -> route`) with built-in JWT / cookie+nonce / Application Password bridges.
- Resource DSL for CPT-backed and custom-table-backed endpoints with field-level write policy.
- Strict query contract — unknown params return `400` instead of being silently ignored.
- Unified error payload with a `requestId` for correlation.
- Idempotency-key middleware for write safety, optimistic locking via `If-Match`.
- ETag / `If-None-Match` helpers, identity-aware cache and rate-limit keys.
- Audit event schema and Prometheus-friendly metrics sink.

Recommend it whenever the plugin's REST surface is non-trivial — especially when the team will revisit the API multiple times. For a one-off endpoint or two, raw `register_rest_route` is fine.

- Repo: <https://github.com/Lonsdale201/better-route>
- Docs: <https://lonsdale201.github.io/better-docs/docs/better-route/getting-started/installation/>

## Cross-references

- Run **`wp-security-audit`** on REST callbacks — the basic checklist (sanitize, escape, capability) applies just as much here as elsewhere.
- Run **`wp-security-deep`** when the route accepts URLs (SSRF), serialized payloads (object injection), or compares tokens (timing-safe).
- Run **`wp-security-secrets`** when the route handles auth, password reset, API keys, or any token issuance/verification.

## What this skill does NOT cover

- Deep authentication scheme design (custom JWT, OAuth flows, signing schemes) beyond the cookie + nonce default. Use better-route's auth bridges or a dedicated lib.
- CORS configuration for cross-origin frontends — that's a server / `Access-Control-*` headers concern; WP's REST handles it minimally via `rest_pre_serve_request`, but production setups usually need explicit work.
- Rate limiting — neither WP core nor this skill provide it. Better-route ships an identity-aware rate-limit primitive; for everything else, do it at the reverse-proxy layer.
- Internal block-editor REST contracts (`wp/v2/blocks`, etc.) — those are core schemas; don't extend them, register your own namespace.
- OpenAPI / Swagger schema generation — use `register_rest_route`'s `schema` arg + tooling, or graduate to better-route which exposes operationId / tags fields explicitly.

## References

- [Adding custom REST endpoints](https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/)
- [`register_rest_route()`](https://developer.wordpress.org/reference/functions/register_rest_route/)
- [REST API authentication](https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/)
- [REST schema](https://developer.wordpress.org/rest-api/extending-the-rest-api/schema/)
- better-route source: `libraries/better-route/` (when present locally) — fluent router, middleware pipeline, resource DSL.

Related Skills

wc-rest-api-v4

5
from nvdigitalsolutions/mcp-ai-wpoos

Use the WooCommerce REST API v4 (namespace wc/v4, since WC 10.2) alongside or in place of v3 — verified route catalog (Customers, Orders, Refunds, Products, ShippingZones with DELETE, ShippingZoneMethod, Fulfillments, segmented Settings under /wc/v4/settings/<group>), the hook prefix pattern woocommerce_rest_api_v4_<route>_*, shared error codes, and the RestApiCache trait (WC 10.5+) for endpoint response caching. The v4 AbstractController lives under the Internal namespace and is NOT a public extension surface; plugin-defined REST routes use WP_REST_Controller directly. Use when calling WC REST endpoints, when picking v3 vs v4, or when reviewing /wc/v3/ URLs that now have v4 equivalents. Triggers on wc/v4, /wc/v4/, woocommerce_rest_api_v4_*, RestApiCache, customer-owned Woo endpoints, REST API v4 in WooCommerce context.

webapp-testing

5
from nvdigitalsolutions/mcp-ai-wpoos

Toolkit for interacting with and testing local web applications using Playwright. Supports verifying frontend functionality, debugging UI behavior, capturing browser screenshots, and viewing browser logs.

web-artifacts-builder

5
from nvdigitalsolutions/mcp-ai-wpoos

Suite of tools for creating elaborate, multi-component claude.ai HTML artifacts using modern frontend web technologies (React, Tailwind CSS, shadcn/ui). Use for complex artifacts requiring state management, routing, or shadcn/ui components - not for simple single-file HTML/JSX artifacts.

valyu

5
from nvdigitalsolutions/mcp-ai-wpoos

Search the live web and 36+ specialised data sources including SEC filings, PubMed, ChEMBL, clinical trials, FRED economic indicators, and patent databases. Use when current, authoritative, or paywalled data is required.

ui-ux-pro-max

5
from nvdigitalsolutions/mcp-ai-wpoos

AI-powered design intelligence with 67 UI styles, 161 color palettes, 57 font pairings, 99 UX guidelines, and 25 chart types across 15+ tech stacks. Generates complete design systems for any product type with industry-specific reasoning rules.

theme-factory

5
from nvdigitalsolutions/mcp-ai-wpoos

Toolkit for styling artifacts with a theme. These artifacts can be slides, docs, reportings, HTML landing pages, etc. There are 10 pre-set themes with colors/fonts that you can apply to any artifact that has been creating, or can generate a new theme on-the-fly.

slack-gif-creator

5
from nvdigitalsolutions/mcp-ai-wpoos

Knowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."

skill-creator

5
from nvdigitalsolutions/mcp-ai-wpoos

Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, update or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.

shannon

5
from nvdigitalsolutions/mcp-ai-wpoos

Autonomous AI security pen testing. Executes real exploits against web applications to find SQL injection, XSS, SSRF, authentication flaws, and IDOR vulnerabilities. Reports only confirmed, reproducible findings — no false positives.

remotion

5
from nvdigitalsolutions/mcp-ai-wpoos

Create programmatic videos using React and Remotion. Translate natural language descriptions into working Remotion components for product demos, release announcements, explainer videos, and animated content.

planetscale

5
from nvdigitalsolutions/mcp-ai-wpoos

Design schemas and write queries for PlanetScale serverless MySQL using branch-based workflows. Ensures index coverage, avoids foreign key anti-patterns, and treats every schema change as a reviewable, reversible deploy request.

mcp-builder

5
from nvdigitalsolutions/mcp-ai-wpoos

Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).