How to create a custom REST API endpoint in WordPress?

Use register_rest_route() inside the rest_api_init action. Always give a permission_callback.

<?php
// A small function, because PHP 8 does not allow is_numeric() directly as the callback:
// WordPress passes 3 values and is_numeric() accepts only one.
function tc_is_number( $value ) {
	return is_numeric( $value );
}

add_action( 'rest_api_init', function () {
	register_rest_route( 'tc/v1', '/sum', array(
		'methods'             => 'GET',
		'permission_callback' => '__return_true',
		'args'                => array(
			'a' => array( 'required' => true, 'validate_callback' => 'tc_is_number' ),
			'b' => array( 'required' => true, 'validate_callback' => 'tc_is_number' ),
		),
		'callback'            => function ( WP_REST_Request $request ) {
			return array( 'sum' => $request['a'] + $request['b'] );
		},
	) );
} );
Terminal output

$ curl -s "http://example.com/wp-json/tc/v1/sum?a=5&b=7"
{"sum":12}
$ curl -s "http://example.com/wp-json/tc/v1/sum?a=5&b=x" | jq -c '{code, message}'
{"code":"rest_invalid_param","message":"Invalid parameter(s): b"}

The route has a namespace (tc/v1), validated parameters and a public permission. Notice the helper function tc_is_number(): with PHP 8, a PHP built in function like is_numeric cannot be used directly as the callback, because WordPress sends three values to it, and the built in function accepts only one. This is a very common cause of the critical error in REST code. Read the full chapter: Custom REST Endpoint.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.