How to Build Custom WordPress REST API Endpoints Safely with permission_callback
Custom WordPress REST API endpoints power headless front ends, block-editor controls, and lightweight AJAX replacements cleanly without hitting admin-ajax.php. Yet broken authorization on custom REST routes remains one of the easiest ways for plugins to leak private data or allow unauthorized edits. Since WordPress 5.5, register_rest_route() triggers a _doing_it_wrong notice if permission_callback is missing—and understanding how permission_callback, args, and WP_REST_Controller work together keeps custom endpoints secure.
Editorial illustration: enforce authorization inside permission_callback and validate/sanitize every parameter in args.
Summary
- Per the WordPress REST API Adding Custom Endpoints handbook, every route registered with
register_rest_route()insiderest_api_initmust define apermission_callback. - Use
__return_trueonly for intentionally public read endpoints; for authenticated writes or private data, checkcurrent_user_can()(and verify object ownership when editing specific posts or orders). - Define
argswithtype,required,validate_callback, andsanitize_callbackso WordPress rejects malformed requests before your callback executes. - Note that browser cookie authentication on the WordPress REST API requires a valid
wp_restnonce (X-WP-Nonceheader) to protect against CSRF—see passing PHP data cleanly withwp_add_inline_script().
How register_rest_route() separates permissions from execution
As documented in WordPress REST API Requests, WP_REST_Server builds a WP_REST_Request object, checks authentication, and runs your permission_callback before your main callback. If permission_callback returns false (or a WP_Error), WordPress aborts immediately with a 401 or 403 JSON response.
Here is a clean example for an endpoint that updates an item owned by an editor:
add_action( 'rest_api_init', function () {
register_rest_route(
'myplugin/v1',
'/notes/(?P<id>\d+)',
array(
'methods' => WP_REST_Server::EDITABLE,
'callback' => 'myplugin_update_note',
'permission_callback' => function ( WP_REST_Request $request ) {
$post_id = (int) $request->get_param( 'id' );
return current_user_can( 'edit_post', $post_id );
},
'args' => array(
'id' => array(
'validate_callback' => function ( $param ) {
return is_numeric( $param ) && (int) $param > 0;
},
),
'summary' => array(
'required' => true,
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
),
),
)
);
} );
Notice two important security habits in those 25 lines:
- Resource-level capability check: Checking
current_user_can( 'edit_post', $post_id )verifies both that the caller is logged in with editing rights and that they are allowed to edit that specific post—preventing Insecure Direct Object Reference (IDOR) bugs where a low-privilege author edits someone else’s draft. - Route-level
argssanitization:summaryis validated as required and passed throughsanitize_text_fieldbeforemyplugin_update_note( WP_REST_Request $request )reads$request->get_param( 'summary' ).
When to extend WP_REST_Controller vs. standalone register_rest_route()
Per WordPress REST API Controller Classes, WP_REST_Controller is an abstract base class useful when your plugin exposes full CRUD resource endpoints (collection GET, single GET, POST, PUT/PATCH, DELETE) with standardized JSON schemas and response links. For one or two small utility endpoints, standalone register_rest_route() calls inside a small class are simpler and avoid unnecessary inheritance coupling.
If your endpoint returns a list of items, also implement pagination headers (X-WP-Total, X-WP-TotalPages) cleanly—see our guide on WordPress REST API pagination.
Step-by-step: Audit custom REST routes in your site
- List all custom routes on staging. Visit
/wp-json/or inspectregister_rest_route(across your custom plugins and themes. - Verify every non-public route has a real capability check. Search for
'permission_callback' => '__return_true'and confirm each match is truly meant for anonymous public reads (neverPOST/DELETEmutations or private user data). - Check nonce handling for logged-in front-end requests. When calling a custom REST route from browser JavaScript for logged-in users, send
X-WP-Nonce: myConfig.nonce(wp_create_nonce( 'wp_rest' )) so WordPress authenticates the cookie session safely. - Verify database queries and backups. Any custom SQL inside a REST callback should use
wpdb::prepare(), and always test plugin changes on staging with a WordPress backup restore rehearsal.
Common mistakes
- Checking
is_user_logged_in()as the onlypermission_callbackon admin actions. Any subscriber on a membership or WooCommerce site is “logged in”! Always check a specific capability likecurrent_user_can( 'manage_options' )oredit_post. - Returning
0orfalsedirectly from a callback instead ofrest_ensure_response()orWP_Error. Usenew WP_Error( 'invalid_item', __( 'Item not found.', 'myplugin' ), array( 'status' => 404 ) )for consistent HTTP status codes. - Caching authenticated REST responses at the Cloudflare edge. Never cache
/wp-json/myplugin/endpoints that check cookies orcurrent_user_can()in Cloudflare Cache Rules—see migrating Page Rules to Cache Rules safely.
Why this matters
Unlike wp-admin screens that automatically verify admin capabilities on load, REST API endpoints are exposed directly at /wp-json/... to the entire internet. A missing permission_callback or weak is_user_logged_in() check turns an internal helper into a public API flaw.
My Take
Treat permission_callback with the exact same strictness as register_setting() sanitization: never write __return_true on a POST, PUT, or DELETE route unless it is an explicitly public submission form (paired with Cloudflare Turnstile or rate limiting), and always test unauthorized curl requests without cookies to confirm you get 401 or 403.
Conclusion
Register custom WordPress REST endpoints on rest_api_init with explicit capability checks in permission_callback, validate and sanitize inputs in args, return structured rest_ensure_response() or WP_Error objects, and verify unauthenticated curl calls return 401/403 on staging.