Drupal - REST GET without caching

You want to read the Cacheability documentation. it says render arrays, but it also applies to response objects.

ResourceResponse implements CacheableResponseInterface, which has the addCacheableDependency method.

If in any way possible, you want to avoid disabling the cache (which you would do by setting the cache max age to 0), but add the necessary cache contexts and cache tags.

In your cache, that means all you need to do is $response->addCacheableDependency($account).

You also don't need getAccount(), just use currentUser() directly, it's a proxy.


I had the same issue.

After reading through the documentation and looking through this page, I was able to shut off the cache for my custom endpoint. Here's an example of my working code inside the get() function for my endpoint:

$build = array(
  '#cache' => array(
    'max-age' => 0,
  ),
);

return (new ResourceResponse($myResponse))->addCacheableDependency($build);

Adding this for future reference, hope this helps anyone who needs it.

CacheableResponseTrait documentation page


I also had the same issue and the solution for that is:

$response->getCacheableMetadata()->addCacheContexts(['url.query_args', 'url.path']);

You can also see the CacheableMetadata and the cache contexts documentations.

Tags:

8