Skip to content
Tutorials Center
My learning

Topics

Lesson 47 of 68 ยท REST API, AJAX and Blocks

Custom REST Endpoints

Build custom WordPress REST API endpoints with register_rest_route: methods, args validation and sanitizing, permission_callback, WP_Error, schema and versioning.

The core REST routes cover posts, pages, users and terms. As soon as your plugin has its own data or actions, such as "list upcoming events", "subscribe this email" or "mark a book as read", you will want your own route. WordPress makes this a single function call, register_rest_route(), and then does a lot of work for you: it matches the URL, checks the HTTP method, validates and sanitizes arguments, runs your permission check and converts your return value into JSON.

This lesson builds on The REST API. You will learn the shape of a route definition, how arguments are checked, how permissions work, how to return data and errors, and how to name and version a namespace. The real WordPress code is read-only; two runnable stand-ins show the dispatch and validation logic in plain PHP.

Your first route

Routes are registered on the rest_api_init hook:

PHP
add_action( 'rest_api_init', function () {
	register_rest_route( 'northwind/v1', '/books', array(
		'methods'             => WP_REST_Server::READABLE, // GET
		'callback'            => 'nw_list_books',
		'permission_callback' => '__return_true',
	) );
} );

function nw_list_books( WP_REST_Request $request ) {
	$books = array(
		array( 'id' => 1, 'title' => 'Dune' ),
		array( 'id' => 2, 'title' => 'Emma' ),
	);
	return rest_ensure_response( $books );
}

That makes GET /wp-json/northwind/v1/books return the array as JSON. The pieces:

  • Namespace (northwind/v1): your vendor or plugin name plus a version. It keeps your routes separate from everyone else's.
  • Route (/books): the path inside the namespace. It can contain a regular expression with a named group, such as /books/(?P<id>\d+), and the captured value becomes a request parameter.
  • methods: one or more of GET, POST, PUT, PATCH, DELETE. The constants WP_REST_Server::READABLE, CREATABLE, EDITABLE and DELETABLE stand for the usual groups, or you can write a string such as 'GET' or 'POST, PUT'.
  • callback: the function that handles the request. It receives a WP_REST_Request.
  • permission_callback: who may call it. Required since WordPress 5.5: if you leave it out, WordPress emits a notice. For a public route you say so explicitly with '__return_true'.

A single route may have several handlers, one per method, by passing an array of definitions:

PHP
register_rest_route( 'northwind/v1', '/books/(?P<id>\d+)', array(
	array(
		'methods'             => WP_REST_Server::READABLE,
		'callback'            => 'nw_get_book',
		'permission_callback' => '__return_true',
	),
	array(
		'methods'             => WP_REST_Server::DELETABLE,
		'callback'            => 'nw_delete_book',
		'permission_callback' => function () {
			return current_user_can( 'delete_posts' );
		},
	),
) );

If a URL matches a route but the HTTP method is not allowed, WordPress returns a "no route found" error (HTTP 404, code rest_no_route) rather than a 405.

flowchart TD
    R["HTTP request to /wp-json/northwind/v1/books/7"] --> M{"Route and<br/>method match?"}
    M -->|"no"| E1["404 rest_no_route"]
    M -->|"yes"| A["Validate and sanitize args"]
    A -->|"invalid"| E2["400 rest_invalid_param"]
    A -->|"ok"| P{"permission_callback<br/>allows?"}
    P -->|"no"| E3["401 or 403 error"]
    P -->|"yes"| C["Run callback"]
    C --> J["Return data as JSON"]

A request passes through matching, argument checks and a permission check before your callback runs.

The request object

WP_REST_Request gives you everything about the call:

PHP
function nw_get_book( WP_REST_Request $request ) {
	$id     = (int) $request['id'];                  // URL or query parameter
	$id2    = $request->get_param( 'id' );           // same thing
	$body   = $request->get_json_params();           // parsed JSON body
	$type   = $request->get_header( 'content-type');
	$method = $request->get_method();
	// ...
}

$request['name'] and get_param() look in the URL route parameters, the query string and the body. If you only want values that went through the argument rules you declared (next section), read them from the request instead of $_GET or $_POST: never touch the superglobals in a REST callback.

Declaring and checking arguments

The args key describes each parameter. WordPress validates and sanitizes them before your callback runs, so the callback can trust what it receives:

PHP
register_rest_route( 'northwind/v1', '/books', array(
	'methods'             => WP_REST_Server::CREATABLE,
	'callback'            => 'nw_create_book',
	'permission_callback' => function () {
		return current_user_can( 'edit_posts' );
	},
	'args'                => array(
		'title'  => array(
			'type'              => 'string',
			'required'          => true,
			'sanitize_callback' => 'sanitize_text_field',
			'validate_callback' => function ( $value ) {
				return is_string( $value ) && strlen( trim( $value ) ) > 1;
			},
		),
		'rating' => array(
			'type'    => 'integer',
			'default' => 3,
			'minimum' => 1,
			'maximum' => 5,
		),
		'status' => array(
			'type' => 'string',
			'enum' => array( 'to-read', 'reading', 'done' ),
		),
	),
) );

What each setting does:

  • type, enum, minimum, maximum, format and similar keys are JSON Schema rules. WordPress validates against them for you, using rest_validate_request_arg() by default.
  • required => true rejects the request if the parameter is missing.
  • default is used when the parameter is absent.
  • validate_callback is your own check. Return true for valid values and false (or a WP_Error) for invalid ones.
  • sanitize_callback cleans the value. It runs after validation, so it receives a value that already passed.

An invalid request never reaches your callback: WordPress answers with HTTP 400 and the code rest_invalid_param, listing which parameters failed. Remember the rule from Sanitizing and Validating Input: validating says "is this acceptable?", sanitizing says "make it safe".

Permissions

The permission_callback decides whether the caller may run the handler at all. It receives the same request object and returns true, false or a WP_Error:

PHP
'permission_callback' => function ( WP_REST_Request $request ) {
	if ( ! is_user_logged_in() ) {
		return new WP_Error(
			'nw_not_logged_in',
			'You must be logged in.',
			array( 'status' => 401 )
		);
	}
	return current_user_can( 'edit_posts' );
},

If the callback returns false, WordPress answers with 401 for visitors who are not logged in and 403 for logged-in users who lack permission. Returning a WP_Error lets you choose the message and status yourself.

Three practices matter here:

  • Never use '__return_true' for anything that writes data or reveals private data. It is for genuinely public reads.
  • Check capabilities, not "is logged in". A subscriber is logged in too. See Users, Roles and Capabilities.
  • Check object-level permission for item routes. "Can edit posts" is not the same as "can edit post 7". Use current_user_can( 'edit_post', $id ), which takes ownership and status into account.

When requests come from the browser with cookie authentication, the X-WP-Nonce header is what proves the request is intentional; that part is handled before your permission callback sees it, as covered in the previous lesson.

Returning data and errors

Your callback may return plain data (arrays, objects, scalars), a WP_REST_Response when you need control over status or headers, or a WP_Error for failures:

PHP
function nw_get_book( WP_REST_Request $request ) {
	$book = nw_find_book( (int) $request['id'] );

	if ( ! $book ) {
		return new WP_Error(
			'nw_book_not_found',
			'No book with that ID.',
			array( 'status' => 404 )
		);
	}

	$response = new WP_REST_Response( $book );
	$response->set_status( 200 );
	$response->header( 'X-Northwind-Source', 'database' );
	return $response;
}

function nw_create_book( WP_REST_Request $request ) {
	$id   = nw_insert_book( $request['title'], $request['rating'] );
	$resp = new WP_REST_Response( array( 'id' => $id ), 201 );
	$resp->header( 'Location', rest_url( 'northwind/v1/books/' . $id ) );
	return $resp;
}

A WP_Error becomes a JSON object with code, message and data (which holds the status). Use real HTTP statuses: 201 for created, 400 for bad input, 401/403 for auth problems, 404 for not found. Never echo or die() inside a callback; return something and let WordPress serialize it.

Schema

Endpoints can describe their output with a JSON Schema, which powers documentation and the OPTIONS request for your route:

PHP
'schema' => 'nw_book_schema',

function nw_book_schema() {
	return array(
		'$schema'    => 'http://json-schema.org/draft-04/schema#',
		'title'      => 'book',
		'type'       => 'object',
		'properties' => array(
			'id'    => array( 'type' => 'integer', 'readonly' => true ),
			'title' => array( 'type' => 'string' ),
		),
	);
}

For a full resource you would write a controller class that extends WP_REST_Controller, which gives you conventions for get_items, get_item, create_item and the schema. For one or two routes, plain register_rest_route() calls are fine.

Namespacing and versioning

Pick the namespace once and keep it: vendor/v1. When you must make a breaking change (rename a field, change a meaning), publish the new behavior under vendor/v2 and keep v1 alive for a while, so apps that call it do not break. Additive changes, such as a new optional field, do not need a new version. Do not use the wp/ namespace for your own routes; it belongs to core.

Stand-in 1: a tiny router

The first TryIt is a router in plain PHP that mimics the flow in the diagram: match the route (with a named capture) and the method, check permission, validate and sanitize args, and return a status and body, with errors shaped like WP_Error. The order of the permission and argument checks is our own choice here. It is not WordPress code.

PHP A router with args and permission callbacks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the output from top to bottom: an anonymous POST is a 401, a logged-in user without edit_posts is a 403, a bad rating is a 400, a missing title is a 400, the title loses its tags and the rating string is cast to the integer 5 for an allowed editor, and an unsupported method on a known URL is the "no route" 404 mentioned earlier.

Stand-in 2: schema-style argument rules

Real WordPress validates type, enum, minimum and maximum for you. The second TryIt reimplements a small version of that to show how declarative rules replace hand-written checks. It reports every problem at once, as the real server does with rest_invalid_param.

PHP Declarative argument validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Request 2 shows default at work, and request 3 shows several errors reported together. Declaring rules like this also documents your endpoint, and keeps validation in one place instead of scattered through callbacks.

Common mistakes

  • Omitting permission_callback, which produces a notice and leaves the intent unclear.
  • Using __return_true on a route that changes data.
  • Reading $_POST or $_GET instead of the request object.
  • Returning HTML or calling die(); return data or a WP_Error.
  • Trusting args for security: validation says the input has the right shape, not that the user may do the action. Always pair it with a permission check.
  • Registering routes outside rest_api_init.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. On which hook should register_rest_route() be called?

    Routes are registered on rest_api_init, which runs when the REST server is set up.
  2. 2. What should the permission_callback of a route that publicly lists books return?

    permission_callback is required. A deliberately public read says so with __return_true. Leaving it out triggers a notice.
  3. 3. A request sends rating=9 but the arg declares maximum 5. What happens?

    Arguments are validated before the callback; invalid input produces a 400 error with the failing parameter named.
  4. 4. How do you report 'book not found' from a callback?

    A returned WP_Error is converted to a JSON error with the HTTP status you provide in its data.
  5. 5. Why is validate-only 'args' not enough to secure a write endpoint?

    Args rules prove the data is well formed. Authorization needs a capability check in permission_callback.

Summary

  • Register routes on rest_api_init with register_rest_route( $namespace, $route, $args ); use vendor/v1 namespaces and keep wp/ for core.
  • methods, callback and a mandatory permission_callback define a handler; routes can contain named regex captures such as (?P<id>\d+).
  • args entries use type, required, default, enum, minimum, maximum, validate_callback and sanitize_callback; invalid input yields a 400 before your code runs.
  • permission_callback returns true, false or a WP_Error; use capabilities and object-level checks, and never __return_true for writes.
  • Return arrays, a WP_REST_Response for custom status and headers, or a WP_Error for failures; never echo or die.
  • Version breaking changes with a new namespace (v2) and add a schema to document responses.

Next you will see the older way to talk to the server from the browser, and when to choose it: AJAX in WordPress.