Checking if HTTP Request is for WordPress REST API

When developing any type of software, you always want to keep your runtime code to a minimum. Functions should only be loaded and run if its necessary to save on resources. This is especially important on the WordPress platform.

WordPress gives you a set of contextual functions to let you know if you’re in different parts of the platform. There’s is_admin(), is_single(), is_home(), and many more. However, WordPress shockingly doesn’t have a function to tell you if the request is being made through the REST API as of this blog post (WordPress 5.7.)

Below is a modified function that you can use to know whether or not the HTTP request is being made on a REST API url.

function is_rest_request() {

   if ( empty( $_SERVER['REQUEST_URI'] ) ) {
     return false;
   }

   $rest_prefix = trailingslashit( rest_get_url_prefix() );
   $is_rest_request = strpos( $_SERVER["REQUEST_URI"], $rest_prefix ) !== false;

   return apply_filters( 
     "is_rest_api_request", 
     $is_rest_request 
   ); 

}

This code is actually borrowed from Woocommerce’s is_rest_api_request(). A few changes have been made but what it effectively does is check if the request uri contains what the site’s rest prefix is set to. This is the tricky part as WordPress, depending on its configuration can have its rest prefix be either /wp-json/ or ?rest_route=….

Be sure to note that there’s a filter you can hook into here: is_rest_api_request.

If implementing this, make sure to put it into a class with a namespace so you don’t have any code collissions; or, prefix the function with something that will ensure it won’t collide with another plugin that might have the same function name.

If you’re lazy and your plugin requires Woocommerce, you can just use the is_rest_api_request() function available through the Woocommerce class.