Register Custom REST API Endpoints with Authentication and Schema Validation in WordPress

Register custom REST API endpoints with authentication and schema validation

register_rest_route() adds your own endpoints to the WordPress REST API. A route has a namespace (by convention myplugin/v1), a path (with optional regex parameters) and one or more handlers, each with HTTP methods, a callback, a permission callback and a description of the parameters. The permission and the parameters are the part that matters for security: WordPress checks them before your callback runs.

Problem: A custom endpoint without a permission check and without a parameter schema is open to anyone and accepts arbitrary input.

Solution: Register the route on rest_api_init with an explicit permission_callback, describe every parameter in args (type, limits, enum, default), and return a WP_REST_Response with the right status code or a WP_Error.

Register a route with GET and POST

<?php
add_action( 'rest_api_init', function () {
    register_rest_route( 'myplugin/v1', '/items', array(
        // GET /wp-json/myplugin/v1/items
        array(
            'methods'             => WP_REST_Server::READABLE,
            'callback'            => 'myplugin_get_items',
            'permission_callback' => '__return_true', // public read
            'args'                => array(
                'per_page' => array(
                    'type'    => 'integer',
                    'default' => 10,
                    'minimum' => 1,
                    'maximum' => 100,
                ),
                'search' => array(
                    'type'              => 'string',
                    'default'           => '',
                    'sanitize_callback' => 'sanitize_text_field',
                ),
            ),
        ),
        // POST /wp-json/myplugin/v1/items
        array(
            'methods'             => WP_REST_Server::CREATABLE,
            'callback'            => 'myplugin_create_item',
            'permission_callback' => function () {
                return current_user_can( 'edit_posts' );
            },
            'args'                => array(
                'title' => array(
                    'type'      => 'string',
                    'required'  => true,
                    'minLength' => 3,
                    'maxLength' => 200,
                ),
                'status' => array(
                    'type'    => 'string',
                    'enum'    => array( 'active', 'inactive', 'draft' ),
                    'default' => 'draft',
                ),
            ),
        ),
    ) );
} );

When a parameter has no own validate_callback and sanitize_callback, WordPress validates and sanitizes it against the schema itself: type, minimum/maximum, minLength/maxLength, enum, format. An invalid request gets 400 with a message naming the parameter, and the callback is not called. Add your own callbacks only for rules the schema cannot describe, and keep in mind that a custom validate_callback replaces the schema validation of that parameter. It should return true or a WP_Error with a clear message.

permission_callback is required since WordPress 5.5: without it the route still works, but WordPress writes a notice. For a public endpoint say so explicitly with '__return_true'.

The callbacks

<?php
function myplugin_get_items( WP_REST_Request $request ) {
    $per_page = $request->get_param( 'per_page' ); // validated: 1..100
    $search   = $request->get_param( 'search' );

    $items = array(); // query your post type or table here

    return rest_ensure_response( $items );
}

function myplugin_create_item( WP_REST_Request $request ) {
    global $wpdb;

    $inserted = $wpdb->insert(
        $wpdb->prefix . 'myplugin_items',
        array(
            'title'      => sanitize_text_field( $request->get_param( 'title' ) ),
            'status'     => $request->get_param( 'status' ),
            'created_at' => current_time( 'mysql', true ),
        ),
        array( '%s', '%s', '%s' )
    );

    if ( false === $inserted ) {
        return new WP_Error( 'myplugin_db_error', 'Could not save the item.', array( 'status' => 500 ) );
    }

    return new WP_REST_Response( array( 'id' => $wpdb->insert_id ), 201 );
}

Status codes: 200 for a read or an update, 201 for a created resource, 204 or 200 with the deleted object for a delete. A WP_Error with 'status' in its data becomes an error response with that code.

Authentication

  • From the site’s own JavaScript: cookie authentication with the wp_rest nonce in the X-WP-Nonce header. Without the nonce, the request is treated as anonymous.
  • From other servers and apps: Application Passwords (WordPress 5.6+) as HTTP Basic authentication, Authorization: Basic base64( user:application-password ), over HTTPS only.

NOTE: An OPTIONS request to the route returns its schema, and /wp-json/myplugin/v1 lists the routes of the namespace, so clients can discover the parameters. The editor uses the same mechanics for dynamic blocks, see building a dynamic Gutenberg block.