One of the most important point while creating custom REST resource endpoint in Drupal 8 is to use the native functions properly.

Did you try for a token replacement and end up in the following error ?

 The controller result claims to be providing relevant cache metadata, but leaked metadata was detected. 
Please ensure you are not rendering content too early.
Returned object class: Drupal\\rest\\ResourceResponse." at core/lib/Drupal/Core/EventSubscriber/EarlyRenderingControllerWrapperSubscriber.php line 154

In normal cases below code should work ;

$token_service = \Drupal::token() ;
$token_replaced = $token_service->replace($string,['node' => $node_object ]);

But if you are ended up with the above error while using token replacment function in a REST resource end point try to update the code like this;

Add it to the top of the page,

use Drupal\Core\Render\BubbleableMetadata;


$bubbleable_metadata = new BubbleableMetadata();
$token_service = \Drupal::token();
$token_replaced = $token_service->replace($string, ['node' => $node_object ],[],$bubbleable_metadata );

BubbleableMetadata(), is an object to which static::generate() and the hooks and functions that it invokes will add their required bubbleable metadata.

This will ensure that the metadata associated with the token replacements gets attached to the same caller return value that contains the token-replaced text.