Rest API Custom Endpoint with space character

You can do this like this:

function get_custom_search_callback($request) {
    //$parameters = $request->get_params();
    $response = urldecode($request->get_param('search'));

    return rest_ensure_response($response);
}

add_action('rest_api_init', 'add_custom_users_api');
function add_custom_users_api(){
    register_rest_route('namespace/v1',
                        'custom-search/(?P<search>([a-zA-Z]|%20)+)',
                        array(
                            'methods' => 'GET',
                            'callback' => 'get_custom_search_callback'
                        )
                    );
}

Note two things:

  • you have to add %20 to the matched character set
  • you have to urldecode() the search variable value to get rid of the %20 and possibly other urlencoded characters (if you put it in the regex)