plugin development – Run different permission_callback depending on HTTP method of custom REST API endpoint – WordPress Development Stack Exchange


Suppose you register a custom endpoint via register_rest_route, and you register multiple different HTTP methods to that endpoint, thus each with its own methods and callback keys, exactly as defined here. What if you want the permission check to depend on the HTTP method. E.g.:

  • If it’s a GET request, do no permission checks.

  • If it’s a POST request, check if $request['fruit'] is Bananas. If yes, grant permission, otherwise not. Stupid example, but it’s just to illustrate my problem, with thus the following code (slightly modified from the referenced link):

function prefix_register_product_routes() {
    register_rest_route( 'my-shop/v1', '/products', array(
            'methods'  => 'GET',
            'callback' => 'process_get',
            'permission_callback' => '__return_true'
            'methods'  => WP_REST_Server::CREATABLE,
            'callback' => 'process_post',
            'permission_callback' => function($request) {return $request['fruit'] === 'Bananas';}
    ) );

add_action( 'rest_api_init', 'prefix_register_product_routes' );

If you now fire a GET request to my-shop/v1, WP seems to execute the permission callback hooked to the POST endpoint, as it returns a 500 error, saying that $request['fruit'] is null. Removing the permission_callback from the POST endpoint avoids this error.

Is this the default behaviour, or am I doing something wrong? It is really common in REST API Designs to have different permission conditions, depending on the HTTP method?! Is this not possible in the WP REST API?

DevelJoe 2 months 2023-04-02T14:54:30-05:00 0 Answers 0 views 0

Leave an answer