Rest API Custom Endpoint with space character

I’m trying to add an endpoint with the following:

register_rest_route('namespace/v1','custom-search/(?P<search>[a-zA-Z\s]+)',
        array(
            'methods' => 'GET',
            'callback' => 'gm_custom_search_callback'
        )
    );

It registers the route, but won’t recognise when I add a space character i.e. %20 or pass a string with a ” ” in, I can’t see anywhere that would suggest how this should be achieved, am I missing something?

1 Answer
1

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)

Leave a Comment