2

I am not sure this is even supposed to happen, but it looks like Drupal is caching REST API responses. I have created a module that makes certain data available through the REST API, and changing the value in the DB requires clearing the cache for it to be reflected immediately in the API response.

Is there a way to prevent Drupal from doing this? The idea behind my API responses is that they are supposed to return real-time data. Currently I'm talking about the user.data service (users_data table), but an answer for any arbitrary data would be appreciated.

A specific random example of what retrieving the data looks like:

$user_data = \Drupal::service('user.data')->get('my_module', $id);

It looks like the cache I want to avoid is stored in cache_dynamic_page_cache.

EDIT: The simplest API response in this case (in the get() method) is:

return new ResourceResponse($user_data);
  • 1
    Could you please also provide some of your controller's response (API) code? – leymannx May 27 '18 at 14:29
  • It's just the ResourceResponse for this data. I have added this to the question. There are some data integrity checks I didn't include, and it will be more complicated in the future, but these two lines are enough to completely reproduce the issue. – Ynhockey May 27 '18 at 15:45
  • 2
    A ResourceResponse is cacheable by default. So either fill in the correct cache metadata as @sonfd suggested, see drupal.stackexchange.com/questions/219239/… how to add it to the response or use an uncacheable Response. – 4k4 May 27 '18 at 15:58
2

I think you need to define #cache settings in your controller's response. You could define it in such a way that your response isn't cached at all, but you're probably better off defining cache tags in such a way that the cache is cleared when the entity is updated. See the Cache API documentation for more info.

Based on the information you've given, I think you'll probably want something like below added to your response array.

'#cache' => [
  'keys' => [
    'MY_MODULE_WHATEVER_KEY_YOU_LIKE',
  ],
  'tags' => [
    'user:' . $id,
  ],
  'max-age' => Cache::PERMANENT,
],

You'll need this use statement at the top of your file for Cache::PERMANENT

use Drupal\Cache\Cache\Cache.php;

The above will cache your response permanently, but break the cache when the user with $id is updated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.