WordPress Rest API custom endpoint optional param

Is it possible to use register_rest_route() with optional parameters in url?

Let’s say route is registered this way:

register_rest_route( 'api', '/animals/(?P<id>\d+)', [
   'methods' => WP_REST_Server::READABLE,
   'callback' => 'get_animals',
   'args' => [
        'id'
    ],
] );

It’s now possible to perform api call on url like /wp-json/api/animals/15, but is there a way to declare the param as optional to also catch route like /wp-json/api/animals/.

I also tried declaring the route like below, but without success:

/animals/(?P<id>\d+)?

You can declare another route without the param or utilize GET params, but is there a way to do this already in the register_rest_route() ?

Thanks for your suggestions.

2

You should put the named parameters of the route regex into an optional capturing group:

register_rest_route( 'api', '/animals(?:/(?P<id>\d+))?', [
   'methods' => WP_REST_Server::READABLE,
   'callback' => 'get_animals',
   'args' => [
        'id'
    ],
] );

The second parameter is simply a regex, thus you can use normal regex logic to make it more complex

Leave a Comment