I have been working on quite an ambitious WordPress project that has a lot of custom REST API endpoints to work alongside an Aurelia SPA application running on top of WordPress.
In this project, I am working with a location JSON file which is 34mb in size. Returning the entire file contents would be a disaster, so I created an endpoint with the ability to search this endpoint. As you might have learned if you are reading this, search queries can sometimes have spaces.
The space in a URL is denoted by the following
%20 in between each word. My URL looks something like this:
If you attempt to create an endpoint, you are probably going to run into an error (a 404) as the space won’t be parsed and the URL won’t be recognised as being valid.
Here is how I solved this issue
register_rest_route( 'utilities/v1', '/locations/(?P<region>([a-zA-Z]|%20)+)', array( 'methods' => 'GET', 'callback' => 'rest_get_locations', ) );
Notice I am including the
%20 in the regular expression? You need to do this, or it won’t be parsed when the regular expression is being checked to match the URL.
Inside of my callback function, I am also decoding the URL to ensure no special characters remain in the URL.
$region = strtolower(urldecode($request->get_param('region')));