24

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 Answers 2

37

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

5

There may be a way to do it with one register_rest_route function call, I do not know how to do that and it would be ideal. However, duplicating the register_rest_route function call in the hooked method will do what you want.

register_rest_route( 'api', '/animals/', [
   'methods' => WP_REST_Server::READABLE,
   'callback' => 'get_animals'
] );

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

It the get_animals method you'll want to have conditions that handle each case. One for if the id arg is set, and the fallback checks for $_GET variables.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.