• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

I Like Kill Nerds

The blog of Australian Front End / Aurelia Javascript Developer & brewing aficionado Dwayne Charrington // Aurelia.io Core Team member.

  • Home
  • Aurelia 2
  • Aurelia 1
  • About
  • Aurelia 2 Consulting/Freelance Work

WordPress Custom REST API Endpoints With Spaces

Wordpress · January 21, 2021

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: http://somewebsite.com/wp-json/utilities/v1/locations/south%20america

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')));

Dwayne

Leave a Reply Cancel reply

0 Comments
Inline Feedbacks
View all comments

Primary Sidebar

Popular

  • Testing Event Listeners In Jest (Without Using A Library)
  • How To Get The Hash of A File In Node.js
  • Thoughts on the Flipper Zero
  • Waiting for an Element to Exist With JavaScript
  • How To Paginate An Array In Javascript
  • Handling Errors with the Fetch API
  • How To Get Last 4 Digits of A Credit Card Number in Javascript
  • ChatGPT Stopping Part Way Through a Response? Here Is How You Fix It
  • How to Use Neural DSP Archetype Plugins With the Quad Cortex
  • How To Mock uuid In Jest

Recent Comments

  • CJ on Microsoft Modern Wireless Headset Review
  • Dwayne on Microsoft Modern Wireless Headset Review
  • CJ on Microsoft Modern Wireless Headset Review
  • john on Microsoft Modern Wireless Headset Review
  • Dwayne on Why You Should Be Using globalThis Instead of Window In Your Javascript Code

Copyright © 2023 · Dwayne Charrington · Log in

wpDiscuz