Question

I'm trying to register a GET REST API route with multiple parameters with the following code:

register_rest_route( 'myplugin/v1', '/posts/?number=(?P<number>[\d]+)&amp;offset=(?P<offset>[\d]+)&amp;total=(?P<total>[\d]+)', array(
    'methods'             => 'GET',
    'callback'            => 'my_rest_function',
    'permission_callback' => '__return_true',
    'args'                => array(
        'number' => array(
            'validate_callback' => function( $param, $request, $key ) {
                return is_numeric( $param );
            }
        ),
        'offset' => array(
            'validate_callback' => function( $param, $request, $key ) {
                return is_numeric( $param );
            }
        ),
        'total' => array(
            'validate_callback' => function( $param, $request, $key ) {
                return is_numeric( $param );
            }
        ),
    ),
) );

But, when I call it using for example:

https://example.com/wp-json/myplugin/v1/posts/?number=3&offset=0&total=3

I'm getting a No route was found matching the URL and request method. error.

What am I doing wrong?

Was it helpful?

Solution

You don't need to include query parameters in the endpoint. Just the path:

register_rest_route( 'myplugin/v1', '/posts', array(
    'methods'             => 'GET',
    'callback'            => 'my_rest_function',
    'permission_callback' => '__return_true',
    'args'                => array(
        'number' => array(
            'validate_callback' => function( $param, $request, $key ) {
                return is_numeric( $param );
            }
        ),
        'offset' => array(
            'validate_callback' => function( $param, $request, $key ) {
                return is_numeric( $param );
            }
        ),
        'total' => array(
            'validate_callback' => function( $param, $request, $key ) {
                return is_numeric( $param );
            }
        ),
    ),
) );

OTHER TIPS

The request should be a regular expression, but not HTML encoded. So, instead of &amp; simply use &.

Also, the ? at the start of the URL query is interpreted as part of the regular expression, just meaning that the preceding / is optional. You have to escape it:

\/posts\/?number=(?P[\d]+)&offset=(?P[\d]+)&total=(?P[\d]+)

To be absolutely sure you can escape the slashes, too, but AFAIK this is not necessary here.

You can test your regex at Regex101.

Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top