1

I have an API which returns various json, like terms of a vocab, nodes of a type, with specific fields and so on.

Now, in my API I am getting the requested language like so:

$request = \Drupal::request();
$lang = $request->query->get('lang', 'en');

And load the respective translations of the entities.

Now, how can I add that $lang parameter as a cache indicator? So that:

/myapi/nodes?lang=en

creates another cache than:

/myapi/nodes?lang=klingon

Also, is that the right way to deliver language specific content in an API?

3

Add a cache context for the query parameter to the response:

$cache_metadata = (new CacheableMetadata())->addCacheContexts(['url.query_args:lang']);
$response->addCacheableDependency($cache_metadata);

About the second question, when this issue is resolved you can use core REST to deliver translated entities: https://www.drupal.org/node/2135829

2
  • thanks so far! is the cached output automatically delivered or do I have to take care of that in my controller? i've read through core rest api but it i didnt find any useful documentary on how to define which fields should be output in which way...
    – Alex
    Mar 24 '17 at 14:08
  • Also works, at least in rest resource: $response->getCacheableMetadata()->setCacheContexts(['url.query_args:lang']); Jan 22 '20 at 14:54

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.