How to cache a custom rest resource when using Url::fromUri
This is the answer:
Url::fromUri($var)-&gt;toString(TRUE)-&gt;getGeneratedUrl();

Found here: https://www.lullabot.com/articles/early-rendering-a-lesson-in-debugging-drupal-8