11

What is the best way to check whether a request is an API request?

Note that the request might be a custom API request, which means it may be as follows:

mysite.com/wp-json/my_namespace/my_version/my_action

Obviously, I can check whether the API route wp-json, but there should be a built-in function to check that.

I need it to do some hooks such as

add_action('init', 'do_something_only_if_api_request');

function do_something_only_if_api_request()
{
   if ( ! wp_api_request() ) {
     return;
   }
   // do stuff
}
Nizar Blond
  • 1,826
  • 5
  • 20
  • 42

3 Answers3

16

You can check defined('REST_REQUEST'). This constant is defined as true in rest_api_loaded() (and not defined otherwise).

There was a discussion of WP Rest API developers about the introduction of a new function like is_rest_request(). In the end they went for this constant.

Onno
  • 821
  • 10
  • 20
  • 2
    Note that `REST_REQUEST` is only defined during the "wp" action (see https://codex.wordpress.org/Plugin_API/Action_Reference), which is much later than the "init" action. – thespacecamel Jul 19 '21 at 19:16
2

As of December 2016, the REST API documentation is pretty poor regarding everything which doesn't look like an endpoint.

However, a few functions exist and you can find the documentation right in the file as they're very well documented, see: wordpress/wp-includes/rest-api.php

If you want add an action only on an REST API call then you probably want to hook the action: rest_api_init, it would look like:

add_action('rest_api_init', 'do_something_only_if_api_request');

function do_something_only_if_api_request($wp_rest_server)
{

   // do stuff

}

You can find the details in the PHPdoc comment:

    /**
     * Fires when preparing to serve an API request.
     *
     * Endpoint objects should be created and register their hooks on this action rather
     * than another action to ensure they're only loaded when needed.
     *
     * @since 4.4.0
     *
     * @param WP_REST_Server $wp_rest_server Server object.
     */
2Fwebd
  • 2,005
  • 2
  • 15
  • 17
0

In my case, the plugin is doing wp_redirect for users to login page.

I want to avoid this in case that the rest api is called.

So I'm using

if (! strpos( $_SERVER['REQUEST_URI'], 'wp-json')) // It's not a rest-api call
  • What if a page/post URL literally has `wp-json` in it? – mukto90 Feb 14 '23 at 05:38
  • I would check for `REST_REQUEST` first, but in case you need to check before that gets defined, perhaps something like ```if (strpos( $_SERVER['REQUEST_URI'], 'wp-json') == 1) // It is most-likely a rest request``` – Paul May 31 '23 at 23:00