• Resolved richardaubin

    (@richardaubin)


    Hello, I have the following endpoint: ‘products’ in the namespace: ‘wc/v3/ext’

    I am using the following to register the route and enable caching.

    I can access the endpoint successfully; I can confirm through debugging that the namespace and endpoint are added to the allowed endpoints.

    The plugin is activated.

    I have yet to be able to cache a response.

    public static function RegisterRoute( string $namespace, string $endpoint, array $methods, object $handler, bool $enableCache = false ) {

    add_action('rest_api_init', function () use ($namespace, $endpoint, $methods, $handler) {
    register_rest_route($namespace, '/' . $endpoint, array(
    'methods' => $methods,
    'callback' => array($handler, 'wcre_endpoint_callback')
    ));
    });

    if( $enableCache ) {
    add_filter( 'wp_rest_cache/allowed_endpoints', function ($allowed_endpoints) use ($namespace, $endpoint) {
    if ( ! isset ( $allowed_endpoints[ $namespace ] ) || ! in_array( $endpoint, $allowed_endpoints[ $namespace ] ) ) {
    $allowed_endpoints[ $namespace ][] = $endpoint;
    }
    return $allowed_endpoints;
    }, 10, 1 );
    }
    }

    • This topic was modified 3 months, 3 weeks ago by richardaubin.
    • This topic was modified 3 months, 3 weeks ago by richardaubin.
Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter richardaubin

    (@richardaubin)

    Resolved (??): Added the POST method as allowed request method. Maybe include this in the FAQs on the main plugin page.

    Are there any pitfalls that I might encounter with other endpoints by adding POST as an allow request method?

    Plugin Author Richard Korthuis

    (@rockfire)

    Hi @richardaubin

    Thank you for using our plugin!

    Indeed POST requests aren’t cached by default. We only cache GET requests by default. This is because with the WordPress REST API (as with other API’s) you use GET to retrieve data, this is data that can be cached. POST is used to create new records (or in case of the WordPress REST API) to update existing records, usually this isn’t data you want to be cached, since each POST call adds or changes data and therefore the response of the REST API. So to sum it up: GET is to retrieve data, POST should not be used to retrieve data.
    So a pitfall you might encounter by adding POST as an allowed request method is that the POST request of for instance the /wp/v2/posts endpoint is also cached and any additional calls might not have the expected result, since a cache result is returned and no code is executed (i.e. no post is added or updated).

Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.