Score:0

Why aren't my rest responses being cached?

ph flag

I created a simple rest endpoint to test caching and I see the response updating. What is stopping it from being cached?

Here's the rest endpoint code:

<?php

namespace Drupal\nm_base_api\Plugin\rest\resource;

use Drupal\rest\ResourceResponse;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\Core\Cache\CacheableMetaData;



/**
 * This is just an example.
 *
 * @RestResource(
 *   id = "test",
 *   label = @Translation("Test"),
 *   uri_paths = {
 *     "canonical" = "/api/v1/test"
 *   }
 * )
 */
class Test extends ResourceBase {

  /**
   * {@inheritdoc}
   */
  public function get() {
    $response = new ResourceResponse(
      [
        'title' => 'test',
        'time' => time(),
      ]
    );
    $cache_meta_data = new CacheableMetadata();
    $cache_meta_data->setCacheMaxAge(2);
    $response->addCacheableDependency($cache_meta_data);

    return $response;
  }

}

And here's what I see in response:

$curl 'http://base.test:8020/api/v1/test'
{"title":"test","time":1651152255}

$ curl 'http://base.test:8020/api/v1/test'
{"title":"test","time":1651152256}

$ curl 'http://base.test:8020/api/v1/test'
{"title":"test","time":1651152257}
sonfd avatar
in flag
Do you just need to add the correct cache metadata to the response?
4uk4 avatar
cn flag
Does this answer your question? [D8: Unable to set cache max-age on ResourceResponse](https://drupal.stackexchange.com/questions/255579/d8-unable-to-set-cache-max-age-on-resourceresponse)
Lambic avatar
ph flag
That seems to be the opposite, they don't want caching but have it. I want caching but don't have it.
sonfd avatar
in flag
@Lambic - Do you see how they're added cache metadata in that post? That's what you need to do.
Lambic avatar
ph flag
I've tried that, and updated the example above, still no caching happening
4uk4 avatar
cn flag
Might be a local dev setting disabling caching?
Lambic avatar
ph flag
That's possible, so I pushed the code up to a ci instance to test there, and still encountering the same issue. Also we're running redis as a cache backend so possible it's specific to redis.
sonfd avatar
in flag
Are other pages being cached?
Lambic avatar
ph flag
It's actually hard to tell because it's an api driven site with no public content, but I'll play around and see if I can test that.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.