apply_filters( ‘rest_request_before_callbacks’, WP_REST_Response|WP_HTTP_Response|WP_Error|mixed $response, array $handler, WP_REST_Request $request )

Filters the response before executing any REST API callbacks.

Description

Allows plugins to perform additional validation after a request is initialized and matched to a registered route, but before it is executed.

Note that this filter will not be called for requests that fail to authenticate or match to a registered route.

Parameters

$responseWP_REST_Response|WP_HTTP_Response|WP_Error|mixed
Result to send to the client.
Usually a WP_REST_Response or WP_Error.
$handlerarray
Route handler used for the request.
$requestWP_REST_Request
Request used to generate the response.

Source

$response = apply_filters( 'rest_request_before_callbacks', $response, $handler, $request );

Changelog

VersionDescription
4.7.0Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Here is the code I have used to authenticate each request and limit route access using allowed routes set in an array

    /**
     * Callback function to authorize each api requests
     * 
     * @see \WP_REST_Request
     * 
     * @param                  $response
     * @param                  $handler
     * @param \WP_REST_Request $request
     *
     * @return mixed|\WP_Error
     */
    function wpdocs_authorize_api_requests( $response, $handler, WP_REST_Request $request ) {
        // allowed routes
        $routes = array(
            '/wp/v2/posts',
            '/wp/v2/pages',
        );
    
        // check if authorization header is set
        if ( ! $request->get_header( 'authorization' ) ) {
            return new WP_Error( 'authorization', 'Unauthorized access.', array( 'status' => 401 ) );
        }
    
        // check for certain role and allowed route
        if ( !in_array( 'administrator', wp_get_current_user()->roles || ! in_array( $request->get_route(), $routes ) ) {
            return new WP_Error( 'forbidden', 'Access forbidden.', array( 'status' => 403 ) );
        }
    
        return $response;
    
    }
    // authorize each requests
    add_filter( 'rest_request_before_callbacks', 'wpdocs_authorize_api_requests', 10, 3 );

You must log in before being able to contribute a note or feedback.