I am working on REST API and I would really like to be able to use the same mechanism for responses as Drupal uses for cached content.

Unfortunately there is no render cache, everything is JSON responses. So there are no #ccache setting or page cache policy to be applied out of the box.

So I wonder if it is even possible and if so how should I approach it?

What I'm after basically is to cache the responses in the same manner as entities for example. So if the context is specific user and I am displaying entity information I would like to get fresh information if the entity is changed but the same content if not and the user is the same..and so on.

up vote 3 down vote accepted

You have to use a cacheable response and then you can add cacheable metadata from a render array or from an object directly:

use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;

  $response = new CacheableJsonResponse($json, 200);

  $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($content));

  $response->addCacheableDependency($entity);

If you use the core REST API this should already be implemented.

  • Oh, didn't know about that. Will check it out. Thanks. – user21641 Oct 31 '16 at 9:45
  • @4k4 Why I Can not render html first to be able to put in a JSON example to be printed? – BOES Jan 18 '17 at 22:35

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.